引起:java.lang.IllegalArgumentException: Can't get JDBC type for null

Had*_*oop 3 hadoop hive scala apache-spark apache-spark-sql

Null在 spark 中将值加载到数据库时出现以下错误。Datatype目标表是smallint

Caused by: java.lang.IllegalArgumentException: Can't get JDBC type for null
Run Code Online (Sandbox Code Playgroud)

代码 :

val hivedata = spark.sql(s"""select 1 as column1 , B a column2 , NULL as column3 from table""")

hivedata .write.mode(SaveMode.Append).jdbc(url = con, table = targettable, Pconnectionropertiess)
Run Code Online (Sandbox Code Playgroud)

谁能帮帮我吗

Ram*_*ram 6

cast(NULL as smallint)你必须做...这会将 null 转换为short类型,如下面的架构所示。

val df1 =spark.sql(
     " select 1 as column1 , 2 column2 , cast(NULL as smallint) as column3 from table  ")
  df1.show
df1.printSchema()
Run Code Online (Sandbox Code Playgroud)

结果 :

+-------+-------+-------+
|column1|column2|column3|
+-------+-------+-------+
|      1|      2|   null|
+-------+-------+-------+

root
 |-- column1: integer (nullable = false)
 |-- column2: integer (nullable = false)
 |-- column3: short (nullable = true)

Run Code Online (Sandbox Code Playgroud)

否则你的方式将是 nulltype 而不是小 int 类型..

val df1 =spark.sql(" select 1 as column1 , 2 column2 ,  NULL   as column3 from table  ")
  df1.show
df1.printSchema()
Run Code Online (Sandbox Code Playgroud)
+-------+-------+-------+
|column1|column2|column3|
+-------+-------+-------+
|      1|      2|   null|
+-------+-------+-------+

root
 |-- column1: integer (nullable = false)
 |-- column2: integer (nullable = false)
 |-- column3: null (nullable = true)
Run Code Online (Sandbox Code Playgroud)

这就是您收到异常的原因。

  • 如果是,请注意[作为所有者接受答案并投票](https://meta.stackexchange.com/a/5235)是否有用 (3认同)