背景介绍
本次模拟背景,Hive sqls库test表中有5个用户信息,使用Spark计算个数后,存入到MySQL数据库hives库tese1表中。
一、新建Hive中模拟数据
hive> create database sqls;
OK
Time taken: 0.913 seconds
hive> use sqls;
OK
Time taken: 0.025 seconds
hive> create table test(name varchar(255),age int);
OK
Time taken: 0.496 seconds
hive> insert into test values('zs','18');
hive> insert into test values('ls','19');
hive> insert into test values('ww','20');
hive> insert into test values('ll','21');
hive> insert into test values('qq','22');
使用 select * from test; 查看插入的数据
二、新建MySQL表
mysql> create database hives;
Query OK, 1 row affected (0.01 sec)
mysql> use hives;
Database changed
mysql> create table test1 (count int);
Query OK, 0 rows affected (0.02 sec)
使用 select * from test1;查询数据
三、编写Spark代码
def main(args: Array[String]): Unit = {
val SparkConf = new SparkConf().setAppName("A_2").setMaster("local[*]")
val sc = new SparkContext(SparkConf)
//设置MySQL的连接地址,这边使用jdbc进行连接
val url = "jdbc:mysql://192.168.25.20:3306/hives"
//使用jdbc的Properties方法
val prop = new Properties()
//设置账号密码
prop.put("user", "root")
prop.put("password", "123456")
//设置hive的连接
val hives = SparkSession.builder()
.config(SparkConf)
.enableHiveSupport()
.getOrCreate()
//编写SparkSQL语句
hives.sql("use sqls")
val datas = hives.sql(
"""
|SELECT COUNT(*) FROM test
|""".stripMargin)
//输出查询后结果
datas.show()
//将通过SparkSQL查询的结果传入到MySQL中
datas.write.mode("append").jdbc(url, "test1", prop)
}
在IDEA中构建工件后放入到spark-submit中运行即可。