Spark连接数据库方法

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 NameMeaning
urlThe JDBC URL to connect to.
dbtableThe 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.
driverThe 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, numPartitionsThese 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进则不会出现卡住现象


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值