我正在查询mysql表
val url = "jdbc:mysql://XXX-XX-XXX-XX-XX.compute-1.amazonaws.com:3306/pg_partner"
val driver = "com.mysql.jdbc.Driver"
val username = "XXX"
val password = "XXX"
var connection:Connection = DriverManager.getConnection(url, username, password)
val statement = connection.createStatement()
val patnerName = statement.executeQuery("SELECT id,name FROM partner")
我确实在patnerName
得到了我的结果,但我需要转换为Dataframe。
我能够通过以下代码打印数据:
while (patnerName.next) {
val id = patnerName.getString("id")
val name = patnerName.getString("name")
println("id = %s, name = %s".format(id,name))
}
现在如何将patnerName
转换为数据框?
答案 0 :(得分:2)
直接使用Spark功能怎么样?
val jdbcDF = spark.read
.format("jdbc")
.option("url", "jdbc:mysql://XXX-XX-XXX-XX-XX.compute-1.amazonaws.com:3306/")
.option("dbtable", "pg_partner")
.option("user", "XXX")
.option("password", "XXX")
.load()
代码取自here。
答案 1 :(得分:2)
因此,您必须分几个步骤进行操作:
val columns = Seq("id", "name")
val schema = StructType(List(
StructField("id", StringType, nullable = true),
StructField("name", StringType, nullable = true)
))
def parseResultSet(rs: ResultSet): Row = {
val resultSetRecord = columns.map(c => rs.getString(c))
Row(resultSetRecord:_*)
}
def resultSetToIter(rs: ResultSet)(f: ResultSet => Row): Iterator[Row] =
new Iterator[Row] {
def hasNext: Boolean = rs.next()
def next(): Row = f(rs)
}
def parallelizeResultSet(rs: ResultSet, spark: SparkSession): DataFrame = {
val rdd = spark.sparkContext.parallelize(resultSetToIter(rs)(parseResultSet).toSeq)
spark.createDataFrame(rdd, schema) // use the schema you defined in step 1
}
val df: DataFrame = parallelizeResultSet(patner, spark)