【问题标题】:Not able to connect MysqlDB through python spark无法通过python spark连接MysqlDB
【发布时间】:2016-02-05 12:37:11
【问题描述】:

我想将处理后的 rdd 保存到 mysql 表中,因为我正在使用 SparkDataFrame,但出现以下错误

py4j.protocol.Py4JJavaError: An error occurred while calling o216.jdbc.
: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/student?user=root&password=root.

我在 sparkshell 中添加了 mysql-jar

spark-shell --driver-class-path /path-to-mysql-jar/mysql-connectorjava-5.1.38-bin.jar。

    from pyspark import SparkContext
    from datetime import datetime
    import os
    import sys
    from pyspark.sql import SQLContext, Row
    sqlContext = SQLContext(sc)
    file1 = sc.textFile("/home/hadoop/text1").cache()
    file2 = sc.textFile("/home/hadoop/text2").cache()
    file3 = file1.union(file2).coalesce(1).map(lambda line: line.split(','))
    file1.unpersist()
    file2.unpersist()
    result = file3.map(lambda x: (x[0]+', '+x[1],float(x[2]))).reduceByKey(lambda a,b:a+b).sortByKey('true').coalesce(1)
    result = result.map(lambda x:x[0]+','+str(x[1]))\
    schema_site = sqlContext.createDataFrame(result)
    schema_site.registerTempTable("table1")
    mysql_url="jdbc:mysql://localhost:3306/test?user=root&password=root&driver=com.mysql.jdbc.Driver"
    schema_site.write.jdbc(url=mysql_url, table="table1", mode="append")

我正在使用 spark spark-1.5.0-bin-hadoop2.4

还设置 hive 元存储。

那么我如何将我的 RDD 结果加载到 Mysql 表中。

输入文件是

  file1 contents are

  1234567  65656545  12

  1234567  65675859  11 

  file2 contents are,

  1234567  65656545  12

  1234567  65675859  11

 and the resultnat RDD is like

 1234567  65656545 24

 1234567  65675859  22

i created the table in mysql with three colunm,

std_id  std_code  std_res

我想要表格输出,

  std_id  std_code  std_res

  1234567  65656545    24

   1234567  65675859   24

【问题讨论】:

标签: python mysql apache-spark pyspark pyspark-sql


【解决方案1】:

通过添加 --jar /path/to/mysql/connector 来解决它,就像 spark 提交一样,

 ./bin/spark-submit --jars lib/mysql-connector-java-5.1.38-bin.jar sample.py

【讨论】:

  • 知道如何在 PyCharm 中执行此操作吗?
  • 过程相同只需创建你的.py脚本并指定路径
【解决方案2】:

将 jdbc 驱动程序或其他 java 依赖项传递给您的 spark 程序时,您应该使用 --jars 参数。

--jars          要包含在驱动程序和执行程序类路径中的本地 jar 的逗号分隔列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 2017-12-23
    • 2020-05-29
    • 2018-12-30
    • 2011-03-11
    相关资源
    最近更新 更多