赞
踩
对SparkSQL先有一个感性认识。win10下使用了Cmder工具,操作如下:
$ pwd D:\Temp\SparkSQLTest $ dir 2019/12/03 16:11 <DIR> . 2019/12/03 16:11 <DIR> .. 2019/01/25 20:45 789,885 mysql-connector-java-5.1.18.jar $ spark-shell --jars mysql-connector-java-5.1.18.jar --driver-class-path mysql-connector-java-5.1.18.jar 略(打开了spark-shell命令行) scala> val url="jdbc:mysql://localhost:3306/collect-ticket" scala> val username = "root" scala> val password = "123456" scala> import org.apache.spark.rdd.JdbcRDD scala> import java.sql.{Connection, DriverManager, ResultSet} scala> Class.forName("com.mysql.jdbc.Driver").newInstance scala> val myRDD = new JdbcRDD( sc, () => | DriverManager.getConnection(url, username, password) , | "select id, code_name from fin_dict_val where id >= ? AND id <= ? ", | 1, 20, 3, r => r.getLong("id") + ", " + r.getString("code_name")) myRDD: org.apache.spark.rdd.JdbcRDD[String] = JdbcRDD[0] at JdbcRDD at <console>:32 scala> myRDD.foreach(println) 1, xxx(隐藏了公司敏感信息) 7, xxx(隐藏了公司敏感信息) 14, xxx(隐藏了公司敏感信息) 8, xxx(隐藏了公司敏感信息) 2, xxx(隐藏了公司敏感信息) 9, xxx(隐藏了公司敏感信息) 15, xxx(隐藏了公司敏感信息) 16, xxx(隐藏了公司敏感信息) 10, xxx(隐藏了公司敏感信息) 3, xxx(隐藏了公司敏感信息) 11, xxx(隐藏了公司敏感信息) 17, xxx(隐藏了公司敏感信息) 12, xxx(隐藏了公司敏感信息) 4, xxx(隐藏了公司敏感信息) 13, xxx(隐藏了公司敏感信息) 18, xxx(隐藏了公司敏感信息) 5, xxx(隐藏了公司敏感信息) 19, xxx(隐藏了公司敏感信息) 20, xxx(隐藏了公司敏感信息) 6, xxx(隐藏了公司敏感信息) scala> myRDD.saveAsTextFile("folder_01")
在当前目录下,生成了folder_01文件夹,里面有三个输出的数据文件:part-00000、part-00001、part-00002。
1, xxx(隐藏了公司敏感信息)
2, xxx(隐藏了公司敏感信息)
3, xxx(隐藏了公司敏感信息)
4, xxx(隐藏了公司敏感信息)
5, xxx(隐藏了公司敏感信息)
6, xxx(隐藏了公司敏感信息)
7, xxx(隐藏了公司敏感信息)
8, xxx(隐藏了公司敏感信息)
9, xxx(隐藏了公司敏感信息)
10, xxx(隐藏了公司敏感信息)
11, xxx(隐藏了公司敏感信息)
12, xxx(隐藏了公司敏感信息)
13, xxx(隐藏了公司敏感信息)
14, xxx(隐藏了公司敏感信息)
15, xxx(隐藏了公司敏感信息)
16, xxx(隐藏了公司敏感信息)
17, xxx(隐藏了公司敏感信息)
18, xxx(隐藏了公司敏感信息)
19, xxx(隐藏了公司敏感信息)
20, xxx(隐藏了公司敏感信息)
API:
class JdbcRDD[T](
sc : org.apache.spark.SparkContext,
getConnection : scala.Function0[java.sql.Connection],
sql : scala.Predef.String,
lowerBound : scala.Long,
upperBound : scala.Long,
numPartitions : scala.Int,
mapRow : scala.Function1[java.sql.ResultSet, T] = { /* compiled code */ }
)
体会下上述交互式窗口里输入的“1, 20, 3”:
可以将20改为30或40再次执行下,将3改为4或5再次执行下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。