Spark通过JDBC加载部分数据、添加过滤条件

本文介绍如何在SparkSQL中使用JDBC连接MySQL、Oracle、Greenplum等数据库时,通过修改dbtable属性实现数据筛选和字段选择,避免加载全量数据表,提高数据处理效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们需要使用SparkSQL通过JDBC方式连接MySQL、Oracle、Greenplum等来实现对数据的操作时,可能在某些情况下并不需要加载全量的数据表。例如:

  1. 只需要其中的部分字段
  2. 按照条件进行筛选后的数据

此时就需要在JDBC连接时对option(“dbtable”, tablename)属性值进行修改,参看spark官网给出的属性介绍:(spark2.3 jdbc-to-other-databases 详细属性链接

Property NameMeaning
urlThe JDBC URL to connect to. The source-specific connection properties may be specified in the URL. e.g., jdbc:postgresql://localhost/test?user=fred&password=secret
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 to use to connect to this URL.
… …… …

dbtable:应该读取的JDBC表。另外也可以在括号中使用子查询语句,而不是完整的表。

测试代码如下:

object JDBCSource {
	def main(args: Array[String]): Unit = {
	    val conf = new SparkConf().setAppName("Greenplum_test").setMaster("local[*]")
	    val sc = new SparkContext(conf)
	    sc.setLogLevel("WARN")
	    val spark = SparkSession.builder().config(conf).getOrCreate()
	    
	    //由于dbtable被用作SELECT语句的源。如果要填入子查询语句,则应提供别名:
	    val tablename = "(select id,name,gender from test.info where gender='man') temp"
	    
	    val data = spark.sqlContext.read
	      .format("jdbc")
	      .option("driver", "com.mysql.jdbc.Driver")
	      .option("url", "jdbc:mysql://localhost:3306/test")
	      .option("dbtable", tablename)			//将查询语句传入
	      .option("user", "username")
	      .option("password", "password")
	      .load()

	    data.show()
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值