插入 SQL 服务器 table 来自 spark 数据框的选定列

Insert into SQL Server table selected columns from spark dataframe

我有一个 SQL 服务器 table,它的架构与我的数据框不同。我想 select 我的数据框中的一些列并“插入” table 我 select 编辑的值。

基本上类似于下面的代码,但在 pyspark 中:

INSERT INTO Cust_Diff_Schema_tbl
(acct_num, name)
SELECT account_no, name
FROM customers
WHERE customer_id > 5000;

我可以使用 spark.read 使用 jdbc 读取数据。如下所示:

df_s3 = spark.read.format("jdbc")\
                .option("driver", db_driver_name)\
                .option("url", db_url+ ":1433;databaseName="+stage_db)\
                .option("dbtable", tbl_name)\
                .option("query", """(select * from customers)""")\
                .option("user", db_username)\
                .option("password", db_password)\
                .load()
    
    df_s3.printSchema()
    df_s3.show(20)

到 write/append 到 table 的数据 selected 值,我相信我仍然可以使用“df_s3.write”,但我需要一个例子来说明如何使用“.option”函数或其他方法使用插入语句,如果这不起作用。

提前致谢。

//create dataframe

val df = //fetch from  db,read file or other options

df.write.format("jdbc")
      .option("numPartitions", 20)
      .option("batchsize", 10000)
      .option("truncate", "true")
      .option("url", "jdbcURL")
      .option("driver", "Driver name")
      .option("dbtable", "tablename")
      .mode("append")
      .save()