spark连接mysql数据库
2021/5/30 2:25:07
本文主要是介绍spark连接mysql数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.安装启动检查Mysql服务。
netstat -tunlp (3306)
2.spark 连接mysql驱动程序。
–cp /usr/local/hive/lib/mysql-connector-java-5.1.40-bin.jar /usr/local/spark/jars
3.启动 Mysql shell,新建数据库spark,表student。
select * from student;
create database spark; use spark; create table student (id int(4), name char(20), gender char(4), age int(4)); alter table student change id id int auto_increment primary key; insert into student values(1,'Xueqian','F',23); insert into student values(2,'Weiliang','M',24); insert into student values(3,'Rongcheng','M',26); insert into student values(4,'Guanhua','M',27); select * from student;
4.spark读取MySQL数据库中的数据
spark.read.format("jdbc").option("url", "jdbc:mysql://localhost:3306/spark?useSSL=false") ... .load()
spark.read.format("jdbc")\ .option("url", "jdbc:mysql://localhost:3306/spark")\ .option("driver","com.mysql.jdbc.Driver").option("dbtable", "student")\ .option("user", "root")\ .option("password", "1")\ .load()\ .show()
5.spark向MySQL数据库写入数据
studentDF.write.format(‘jdbc’).option(…).mode(‘append’).save()
from pyspark.sql.types import Row,StructField,StringType,StructType,IntegerType #下面设置两条数据,表示两个学生的信息 studentRDD = spark.sparkContext.parallelize(["5 zhao M 26","6 wang M 27"]).map(lambda line:line.split(" ")) #下面创建Row对象,每个Row对象都是rowRDD中的一行 rowRDD = studentRDD.map(lambda p:Row(p[1].strip(),p[2].strip(),int(p[3]))) # 下面设置模式信息 schema = StructType([StructField("name",StringType(),True),StructField("gender",StringType(),True),StructField("age",IntegerType(),True)]) #建立起Row对象和模式之间的对应关系,也就是把数据和模式对应起来 studentDF = spark.createDataFrame(rowRDD,schema) #写入数据库 prop = {} prop['user'] = 'root' prop['password'] = '123456' prop['driver'] = 'com.mysql.jdbc.Driver' studentDF.write.jdbc("jdbc:mysql://localhost:3306/spark?useSSL=false",'student','append',prop)
这篇关于spark连接mysql数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-29阿里 Canal 实时同步 MySQL 增量数据至 ClickHouse 数据库
- 2024-05-24在Linux下管理MySQL的大小写敏感性
- 2024-04-26MySQL查出时间比实际晚8小时的解决方案
- 2024-04-01JPA不识别MySQL的枚举类型
- 2024-03-30mysql数据库表卡死解决方法
- 2024-03-15MySQL多数据源笔记5-ShardingJDBC实战
- 2024-03-11natural join mysql
- 2024-03-11关于VS2017,VS2015 中利用 EF使用Mysql 不显示数据源问题解决方案
- 2024-02-26mysql 阿里云xb后缀备份文件恢复-icode9专业技术文章分享
- 2024-02-22docker mysql 5.7