首页 > 解决方案 > 使用 scala 在函数中将多个 Dataframes 插入到 postgres 表中

问题描述

我有一个功能:

 def PopulatePostgres(df: DataFrame ,df1: DataFrame,df2: DataFrame   table: String): Result = {
    val result = Try({

      df
        .write
        .format("jdbc")
        .mode(SaveMode.Append)
        .option("url", config.url)
        .option("user", config.username)
        .option("password", config.password)
        .option("dbtable", table)
        .option("driver", "org.postgresql.Driver")
        .save()
    })

    result match {
      case Success(_) => Result(s"Created ${table}")
      case Failure(problem) => {
        log.error(problem.getMessage)
        Result(s"Failed to create ${table}")
      }
    }
  }

但是,我不确定如何将 3 个数据帧一一转储到 postgres 表中。所以我需要将 df、df1、df2 全部插入到 postgres 表中。有人可以帮我吗

标签: postgresqlscaladataframeapache-spark

解决方案


如果要将所有数据框存储到同一个表中。

val findaldf = df.union(df1).union(df2)

然后你可以使用你的持久性逻辑。

但是所有的df都想单独存储

List(df, df1, df2).map(_.write.format("jdbc")
        .mode(SaveMode.Append)
        .option("url", config.url)
        .option("user", config.username)
        .option("password", config.password)
        .option("dbtable", table)
        .option("driver", "org.postgresql.Driver")
        .save()) 


推荐阅读