如何使用 int 和 varchar 列以附加模式将 "all string" 数据帧写入 Spark JDBC 到目标 table

How to write "all string" dataframe to Spark JDBC in Append mode to a target table with int and varchar columns

我从 c​​sv 文件创建 spark 数据帧并尝试将其插入到具有整数和 varchar 列的 rdbms table。由于我的数据框都是字符串类型,因此它在“追加”模式下失败。如果我使用覆盖模式,将使用所有 varchar 列重新创建 rdbms table。如何通过处理 spark 数据帧中的数据类型以追加模式将数据插入 rdbms table?

在读取 CSV 文件时,您可以推断架构或以编程方式指定架构。

val diamonds = sqlContext.read.format("csv")
      .option("delimiter"," ").option("quote","")
      .option("header", "true")
      .option("inferSchema", "true")
      .load("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv");

import org.apache.spark.sql.types._

val customSchema = new StructType()
  .add("_c0",IntegerType,true)
  .add("carat",DoubleType,true)
  .add("cut",StringType,true)
  .add("color",StringType,true)
  .add("clarity",StringType,true)
  .add("depth",DoubleType,true)
  .add("table",DoubleType,true)
  .add("price",IntegerType,true)
  .add("x",DoubleType,true)
  .add("y",DoubleType,true)
  .add("z",DoubleType,true)
    
    val diamonds_with_schema = spark.read.format("csv")
    .option("header", "true")
    .schema(customSchema)
    .load("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv");

一旦您拥有具有所需模式的数据框,您就可以附加到现有的 table。

请检查:https://docs.databricks.com/data/data-sources/read-csv.html