编程实现利用 DataFrame 读写 MySQL 的数据

这是林子雨spark实验5的第三问:配置Spark通过JDBC连接数据库MySQL,编程实现利用DataFrame插入下列数据到MySQL, 最后打印出 age 的最大值和 age 的总和

下面贴出代码(测试过ok)

import java.util.Properties  
import org.apache.spark.sql.types._  
import org.apache.spark.sql.Row  
import org.apache.spark.SparkConf  
import org.apache.spark.SparkContext  
import org.apache.spark.sql.SQLContext  
object TestMySQL {  
  def main(args: Array[String]) {  
    val conf = new SparkConf()  
    conf.setMaster("local")  
      .setAppName("TestMySQL")    //设置运行方式为本地  
    val sc = new SparkContext(conf)  
    var sqlContext = new SQLContext(sc)  
    val employeeRDD = sqlContext.sparkContext.parallelize(Array("3 Mary F 26","4 Tom M 23")).map(_.split(" "))  
    val schema = StructType(List(StructField("id", IntegerType, true),StructField("name", StringType, true),StructField("gender", StringType, true),StructField("age", IntegerType, true)))  
    val rowRDD = employeeRDD.map(p => Row(p(0).toInt,p(1).trim, p(2).trim,p(3).toInt))  
    val employeeDF = sqlContext.createDataFrame(rowRDD, schema)  
    val prop = new Properties()  
    prop.put("user", "root")  
    prop.put("password", "1")  
    prop.put("driver","com.mysql.jdbc.Driver")  
    prop.put("url","jdbc:mysql://192.168.80.128:3306/sparktest")  
    employeeDF.write.mode("append").jdbc("jdbc:mysql://192.168.80.128:3306/sparktest", "sparktest.employee", prop)  
    val jdbcDF = sqlContext.read.format("jdbc").option("url", "jdbc:mysql://192.168.80.128:3306/sparktest").option("driver","com.mysql.jdbc.Driver").option("dbtable","employee").option("user","root").option("password", "1").load()  
    jdbcDF.agg("age" -> "max", "age" -> "sum")  
    jdbcDF.show()  
  
  }  
}

运行截图:

编程实现利用 DataFrame 读写 MySQL 的数据

测试中遇到的问题:

1:mysql服务器拒绝远程连接

解决方法:

授权法

(1)例如,你想myuser使用mypassword从任何主机连接到mysql服务器的话。

第一步:root用户登录;mysql>mysql -u root -p rootpassword;

第二步:赋予权限;mysql>GRANT ALL PRIVILEGES ON *.* TO ‘root‘@‘%‘ IDENTIFIED BY ‘mypassword‘ WITH GRANT OPTION;

第三步:mysql>FLUSH PRIVILEGES;

(2)如果你想允许用户myuser从ip为192.168.1.3的主机连接到mysql服务器,并使用mypassword作为密码

mysql>GRANT ALL PRIVILEGES ON *.* TO ‘root‘@‘192.168.xxx.xxx‘ IDENTIFIED BY ‘mypassword‘ WITH GRANT OPTION;

mysql>FLUSH PRIVILEGES;

(3)如果你想允许用户myuser从ip为192.168.1.3的主机连接到mysql服务器的dk数据库,并使用mypassword作为密码

mysql>GRANT ALL PRIVILEGES ON dk.* TO ‘root‘@‘192.168.xxx.xxx‘ IDENTIFIED BY ‘mypassword‘ WITH GRANT OPTION;

mysql>FLUSH PRIVILEGES;

相关推荐