Home > Software design >  How to connect to Oracle database from Scala and read a huge data
How to connect to Oracle database from Scala and read a huge data

Time:09-28

I am a newbie in Scala. In my program, I want to read a huge data from Oracle table and process them. The code is in following:

import java.sql.Connection
import oracle.jdbc.pool.OracleDataSource
object readTable extends App {
val num = 4
def read_data(group_id: Int):Unit =  {
  val table_name = "table"
  val col_name = "col"
  val query = """ CREATE OR REPLACE FUNCTION func_id(str_id  IN VARCHAR2,
                num_group IN NUMBER)
                RETURN NUMBER
                IS
                BEGIN
                RETURN MOD(TO_NUMBER(substr(str_id, -LEAST(2, LENGTH(str_id)))), num_group);
                END;
                 /
            select * from """   table_name   """ where func_id(""" col_name """,""" num """)=""" group_id
 
  val connection : Connection = null
  val oracleUser = "orcl"
  val oraclePassword = "******"
  val oracleURL = "jdbc:oracle:thin:@//x.x.x.x:1521/orcldb"

  val ods = new OracleDataSource()
  ods.setUser(oracleUser)
  ods.setURL(oracleURL)
  ods.setPassword(oraclePassword)

  val con = ods.getConnection()
  val statement = con.createStatement()

  statement.setFetchSize(1000)      // important

  val  resultSet : java.sql.ResultSet = statement.executeQuery(query)

 do {
  println("enter ******************************* ")
  val cst = resultSet.getString("cst")
  val name = resultSet.getString("name")
  println("cst = %s, name = %s".format(cst,name))
 } while (resultSet.next)

  println("resultset:",resultSet)
 }

  read_data(1) // 1 is just an example
}

When I run it, I receive this error:

Exception in thread "main" java.sql.SQLException: Non supported character set (add orai18n.jar in your classpath): AR8MSWIN1256

Would you please guide me what I am doing wrong?

Any help is really appreciated.

CodePudding user response:

Problem solved. I add these lines to build.sbt and I can connect to the Oracle. Also, I download ojdbc6-11.2.0.1.0.jar and add it to the project folder.

 // https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8
 libraryDependencies  = "com.oracle.database.jdbc" % "ojdbc8" % "21.3.0.0"

// https://mvnrepository.com/artifact/com.oracle.ojdbc/orai18n
 libraryDependencies  = "com.oracle.ojdbc" % "orai18n" %  "19.3.0.0"

These lines are necessary to see the result:

while (resultSet.next){
  val cst = resultSet.getString("cst")
  val name = resultSet.getString("name")
  println("cst = %s, name = %s".format(cst,name))
}
  • Related