spark使用java的api读取mysql的几种方式

该博客展示了如何使用Java编程来连接Spark和MySQL数据库,包括两种方式读取MySQL数据并将其转换为DataFrame,进行数据操作后,再将结果保存回MySQL的方法。示例代码详细演示了配置连接参数、数据读取、DataFrame操作和数据写回的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class CreateDFFromMysql {
public static void main(String[] args) {
SparkConf conf = new SparkConf();
conf.setMaster(“local”).setAppName(“mysql”);
/**
* 配置join或者聚合操作shuffle数据时分区的数量
/
conf.set(“spark.sql.shuffle.partitions”, “1”);
JavaSparkContext sc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(sc);
/
*
* 第一种方式读取MySql数据库表,加载为DataFrame
/
Map<String, String> options = new HashMap<String,String>();
options.put(“url”, “jdbc:mysql://192.168.179.4:3306/spark”);
options.put(“driver”, “com.mysql.jdbc.Driver”);
options.put(“user”, “root”);
options.put(“password”, “root”);
options.put(“dbtable”, “person”);
DataFrame person = sqlContext.read().format(“jdbc”).options(options).load();
person.show();
person.registerTempTable(“person1”);
/
*
* 第二种方式读取MySql数据表加载为DataFrame
*/
DataFrameReader reader = sqlContext.read().format(“jdbc”);
reader.option(“url”, “jdbc:mysql://192.168.179.4:3306/spark”);
reader.option(“driver”, “com.mysql.jdbc.Driver”);
reader.option(“user”, “root”);
reader.option(“password”, “root”);
reader.option(“dbtable”, “score”);
DataFrame score = reader.load();
score.show();
score.registerTempTable(“score1”);

DataFrame result =
sqlContext.sql(“select person1.id,person1.name,person1.age,score1.score "
+ “from person1,score1 "
+ “where person1.name = score1.name”);
result.show();
/**
* 将DataFrame结果保存到Mysql中
/
Properties properties = new Properties();
properties.setProperty(“user”, “root”);
properties.setProperty(“password”, “123456”);
/
*
* SaveMode:
* Overwrite:覆盖
* Append:追加
* ErrorIfExists:如果存在就报错
* Ignore:如果存在就忽略
*
*/
result.write().mode(SaveMode.Overwrite).jdbc(“jdbc:mysql://192.168.179.4:3306/spark”, “result”, properties);
System.out.println(”----Finish----”);
sc.stop();

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值