繁体   English   中英

在scala中写入JDBC源

[英]write to a JDBC source in scala

我正在尝试使用scala编写经典的sql查询,以将一些信息插入sql服务器数据库表中。

与我的数据库的连接运行良好,并且我成功地从JDBC中读取了数据,该数据来自最近创建的名为“ textspark”的表,该表只有1个名为“ firstname”的列create table textspark(firstname varchar(10))

但是,当我尝试将数据写入表时,出现以下错误:

Exception in thread "main" org.apache.spark.sql.AnalysisException: Table or view not found: textspark

这是我的代码:

//Step 1: Check that the JDBC driver is available
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")

//Step 2: Create the JDBC URL
val jdbcHostname = "localhost"
val jdbcPort = 1433
val jdbcDatabase ="mydatabase"
val jdbcUsername = "mylogin"
val jdbcPassword = "mypwd"

// Create the JDBC URL without passing in the user and password parameters.
val jdbcUrl = s"jdbc:sqlserver://${jdbcHostname}:${jdbcPort};database=${jdbcDatabase}"

// Create a Properties() object to hold the parameters.
import java.util.Properties
val connectionProperties = new Properties()

connectionProperties.put("user", s"${jdbcUsername}")
connectionProperties.put("password", s"${jdbcPassword}")

//Step 3: Check connectivity to the SQLServer database
val driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
connectionProperties.setProperty("Driver", driverClass)



//Read data from JDBC
val textspark_table = spark.read.jdbc(jdbcUrl, "textspark", connectionProperties)
textspark_table.show()

//the read operation works perfectly!!


//Write data to JDBC
import org.apache.spark.sql.SaveMode


spark.sql("insert into textspark values('test') ")
     .write
     .mode(SaveMode.Append) // <--- Append to the existing table
     .jdbc(jdbcUrl, "textspark", connectionProperties)

//the write operation generates error!!

谁能帮我解决这个错误?

您无需在Spark使用insert语句。 您指定了附加模式没问题。 您不应插入数据,而应选择/创建数据。 尝试这样的事情:

spark.sql("select 'text'")
  .write
  .mode(SaveMode.Append)
  .jdbc(jdbcUrl, "textspark", connectionProperties)

要么

Seq("test").toDS
  .write
  .mode(SaveMode.Append)
  .jdbc(jdbcUrl, "textspark", connectionProperties)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM