(一)編程實現將 RDD 轉換爲 DataFrame
使用編程接口,構造一個 schema 並將其應用在已知的 RDD 上。
命令:
結果:
數據庫中已有的表:
對此表插入兩個數據操作:
導包:
代碼解說:
1.//下面我們設置兩條數據表示兩個學生信息
2.val studentRDD = spark.sparkContext.parallelize(Array("3 Rongcheng M 26","4 Guanhua M 27")).map(_.split(" "))
3.
4.//下面要設置模式信息
5.val schema = StructType(List(StructField("id", IntegerType, true),StructField("name", StringType, true),StructField("gender", StringType, true),StructField("age", IntegerType, true)))
6.
7.//下面創建Row對象,每個Row對象都是rowRDD中的一行
8.val rowRDD = studentRDD.map(p => Row(p(0).toInt, p(1).trim, p(2).trim, p(3).toInt))
9.
10.//建立起Row對象和模式之間的對應關係,也就是把數據和模式對應起來
11.val studentDF = spark.createDataFrame(rowRDD, schema)
12.
13.//下面創建一個prop變量用來保存JDBC連接參數
14.val prop = new Properties()
15.prop.put("user", "root") //表示用戶名是root
16.prop.put("password", "hadoop") //表示密碼是hadoop
17.prop.put("driver","com.mysql.jdbc.Driver") //表示驅動程序是com.mysql.jdbc.Driver
18.
19.//下面就可以連接數據庫,採用append模式,表示追加記錄到數據庫spark的student表中
20.studentDF.write.mode("append").jdbc("jdbc:mysql://localhost:3306/spark", "spark.student", prop)
21.val jdbcDF = 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", "8186123").load()//配置Spark通過jdbc連接數據庫mysql
22.jdbcDF.agg("age" -> "max", "age" -> "sum").show()//最後打印age的最大值和總和