pyspark连接mysql数据库报错

使用pyspark连接mysql数据库代码如下

spark_conf = SparkConf().setAppName("MyApp").setMaster("local")

spark = SparkSession.builder.config(conf=spark_conf).getOrCreate()

url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false"
table_name = "tab_tf"
properties = {
    "user": "root",
    "password": "root"
}

# 读取 MySQL 数据库中的数据
df = spark.read.jdbc(url=url, table=table_name, properties=properties)
# 展示数据
df.show()

执行时报错了,错误信息如下:

py4j.protocol.Py4JJavaError: An error occurred while calling o32.jdbc.
: java.sql.SQLException: No suitable driver
    at java.sql.DriverManager.getDriver(DriverManager.java:315)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$6.apply(JDBCOptions.scala:105)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$6.apply(JDBCOptions.scala:105)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions.(JDBCOptions.scala:104)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions.(JDBCOptions.scala:35)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:32)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:332)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:242)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:230)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:186)
    at org.apache.spark.sql.DataFrameReader.jdbc(DataFrameReader.scala:257)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
 

经查询,是因为spark中缺少连接MySQL的驱动程序,于是乎下载了与自己mysql数据库版本一致的jar包,下载地址:https://downloads.mysql.com/archives/c-j/ 

查询mysql版本命令:mysql -V

pyspark连接mysql数据库报错_第1张图片

下载完成后,解压,将mysql-connector-java-8.0.30.jar拷贝到spark安装目录的libs中

pyspark连接mysql数据库报错_第2张图片

重新执行程序,问题解决,执行结果如下:

pyspark连接mysql数据库报错_第3张图片

参考:py4j.protocol.Py4JJavaError: An error occurred while calling o32.jdbc.-CSDN博客

你可能感兴趣的:(问题解决,python,pyspark,mysql)