Spark连接数据库方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yvigmmwfn/article/details/45338969

Version:Spark 1.3.0

方法一:

val rdd = new JdbcRDD(sc,()=>{
      Class.forName("com.mysql.jdbc.Driver").newInstance()
      DriverManager.getConnection("url", "user", "password")
    },"select * from table_name where 1 = ? AND 1 = ?",1,1,30
      ,r=>r.getString(1)).cache()

参数说明:

第一个:SparkContext对象

第二个:获取Java中Connection对象连接

第三个:执行SQL语句,####注:必须要接两个参数

第四个:第1个参数值

第五个:第2个参数值

第六个:分区

第七个:返回一个结果集,对结果集进行遍历

返回:JdbcRDD对象


方法二:

val rdd = sqlContext.load("jdbc",Map(
      "url" -> "jdbc:mysql://localhost:3306/test?user=root&password=root",
      "dbtable" -> "schema.table"))

参数说明:

第一个:源名

第二个:创建Map对象设置"url","dbtable",更多如下:

Property Name Meaning
url The JDBC URL to connect to.
dbtable The JDBC table that should be read. Note that anything that is valid in a `FROM` clause of a SQL query can be used. For example, instead of a full table you could also use a subquery in parentheses.
driver The class name of the JDBC driver needed to connect to this URL. This class with be loaded on the master and workers before running an JDBC commands to allow the driver to register itself with the JDBC subsystem.
partitionColumn, lowerBound, upperBound, numPartitions These options must all be specified if any of them is specified. They describe how to partition the table when reading in parallel from multiple workers.partitionColumn must be a numeric column from the table in question.

返回:DataFrame对象



方法三:

val rdd = sqlContext.jdbc("jdbc:mysql://localhost:3306/test?user=root&password=root","schema.test")

参数说明:

第一个:数据库连接字符串

第二个:查询的表名

返回:DataFrame对象


总结:

连接方法一目前本人测试连接关系型数据库,MongoDB都是没有问题的。

连接方法二,方法三目前本人测试连接关系型数据库,但连接MongoDB没有返回结果。个人觉得是无法支持非关系型数据库。

至于Load是不是类似于数据库中的sqlload操作,这个需要测试。


注:本人在连接MongoDB与MySQL时查询出的对DataFrame进行Join运行时则出现卡住现象,但使用RDD进行Join进则不会出现卡住现象


猜你喜欢

转载自blog.csdn.net/yvigmmwfn/article/details/45338969
今日推荐