以下是一段 Scala 代码示例,展示如何读取 TXT 文件中的数据并将其保存到 Oracle 数据库:

import scala.io.Source
import java.sql.{Connection, DriverManager, PreparedStatement}

object TxtToOracle {

  def main(args: Array[String]): Unit = {
    // 数据库连接信息
    val url = 'jdbc:oracle:thin:@localhost:1521:orcl'
    val username = 'username'
    val password = 'password'

    // 读取txt文件内容
    val file = Source.fromFile('data.txt')
    val lines = file.getLines().toList
    file.close()

    // 连接数据库
    val connection = DriverManager.getConnection(url, username, password)

    // 插入数据
    val statement = connection.prepareStatement('INSERT INTO mytable (column1, column2) VALUES (?, ?)')
    for (line <- lines) {
      val parts = line.split(',')
      statement.setString(1, parts(0))
      statement.setString(2, parts(1))
      statement.executeUpdate()
    }

    // 关闭连接
    statement.close()
    connection.close()
  }
}

上述代码中,我们首先使用 Scala 的 Source 对象读取了名为 data.txt 的文件的内容,并将其保存为一个字符串列表。然后,我们使用 Java 的 DriverManager 建立了一个数据库连接,使用 PreparedStatement 对象将数据逐行插入到 Oracle 数据库的 mytable 表中。最后,我们关闭了连接和语句对象。请注意,在实际应用中,我们应该使用更加健壮的错误处理和异常处理机制。

Scala 代码示例:读取 TXT 文件数据并保存到 Oracle 数据库

原文地址: http://www.cveoy.top/t/topic/nsYN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录