spark向MySQL刷新一个字段_Spark 实现MySQL update操作

背景

目前 spark 对 MySQL 的操作只有 Append,Overwrite,ErrorIfExists,Ignore几种表级别的模式,有时我们需要对表进行行级别的操作,比如update。即我们需要构造这样的语句出来:insert into tb (id,name,age) values (?,?,?) on duplicate key update id=?,name =? ,age=?;

需求:我们的目的是既不影响以前写的代码,又不引入新的API,只需新加一个配置如:savemode=update这样的形式来实现。

实践

要满足以上需求,肯定是要改源码的,首先创建自己的saveMode,只是新加了一个Update而已:

public enum I4SaveMode {

Append,

Overwrite,

ErrorIfExists,

Ignore,

Update

}

JDBC数据源的相关实现主要在JdbcRelationProvider里,我们需要关注的是createRelation方法,我们可以在此方法里,把SaveMode改成我们自己的mode,并把mode带到saveTable方法里,所以改造后的方法如下(改了的地方都有注释):

override def createRelation(

sqlContext: SQLContext,

mode: SaveMode,

parameters: Map[String, String],

df: DataFrame): BaseRelation = {

val options = new JDBCOptions(parameters)

val isCaseSensitive = sqlContext.conf.caseSensitiveAnalysis

// 替换成自己的saveMode

var saveMode = mode match {

case SaveMode.Overwrite => I4SaveMode.Overwrite

case SaveMode.Append => I4SaveMode.Append

case SaveMode.ErrorIfExists => I4SaveMode.ErrorIfExists

case SaveMode.Ignore => I4SaveMode.Ignore

}

//重点在这里,检查是否有saveMode=update的参数,并设为对应的模式

val parameterLower = parameters.map(kv => (kv._1.toLowerCase,kv._2))

if(parameterLower.keySet.contains("savemode")){

saveMode = if(parameterLower.get("savemode").get.equals("update")) I4SaveMode.Update else saveMode

}

val conn = JdbcUtils.createConnectionFactory(options)()

try {

val tableExists = JdbcUtils.tableExists(conn, options)

if (tableExists) {

saveMode match {

case I4SaveMode.Overwrite =>

if (options.isTruncate && isCascadingTruncateTable(options.url) == Some(false)) {

// In this case, we should truncate table and then load.

truncateTable(conn, options.table)

val tableSchema = JdbcUtils.getSchemaOption(conn, options)

saveTable(df, tableSchema, isCaseSensitive, options, saveMode)

} else {

......

}

接下来就是saveTable方法:

def saveTable(

df: DataFrame,

tableSchema: Option[StructType],

isCaseSensitive: Boolean,

options: JDBCOptions,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spark中,可以通过JDBC连接MySQL数据库并使用`upsert`语句来执行插入或更新操作。具体实现如下: 1. 导入必要的依赖: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> ``` 2. 创建一个`DataFrame`,并指定`DataFrame`的schema。假设需要将数据插入到名为`users`的MySQL表中,表结构如下: ```sql CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100), age INT, PRIMARY KEY (id) ); ``` 则可以定义如下的schema: ```scala import org.apache.spark.sql.types._ val schema = StructType(Seq( StructField("name", StringType), StructField("age", IntegerType) )) ``` 3. 读取数据并将其转换为`DataFrame`: ```scala val rdd = sc.parallelize(Seq( ("Alice", 25), ("Bob", 30), ("Charlie", 35) )) val df = spark.createDataFrame(rdd).toDF("name", "age") ``` 4. 将`DataFrame`写入到MySQL表中: ```scala val url = "jdbc:mysql://localhost:3306/mydb" val user = "username" val password = "password" df.write .format("jdbc") .option("url", url) .option("dbtable", "users") .option("user", user) .option("password", password) .option("driver", "com.mysql.jdbc.Driver") .option("rewriteBatchedStatements", "true") .option("batchsize", "10000") .mode("append") .save() ``` 在上述代码中,`url`用于指定MySQL数据库的连接地址,`user`和`password`用于指定数据库的用户名和密码,`dbtable`用于指定要写入的表名,`driver`用于指定MySQL的JDBC驱动程序。 `rewriteBatchedStatements`和`batchsize`用于优化写入性能。`rewriteBatchedStatements`设置为`true`时,表示使用批量写入模式,可以提高写入性能。`batchsize`用于指定每批次写入的记录数。 5. 如果需要执行`upsert`操作,则可以使用MySQL的`REPLACE INTO`语句或`ON DUPLICATE KEY UPDATE`语句。例如,如果需要根据`name`字段更新记录,则可以使用如下的SQL语句: ```sql INSERT INTO users (name, age) VALUES (?, ?) ON DUPLICATE KEY UPDATE age=VALUES(age) ``` 在Spark中,可以通过以下方式执行`upsert`操作: ```scala df.write .format("jdbc") .option("url", url) .option("dbtable", "users") .option("user", user) .option("password", password) .option("driver", "com.mysql.jdbc.Driver") .option("rewriteBatchedStatements", "true") .option("batchsize", "10000") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .option("rewriteBatchedStatements", "true") .mode("append") .jdbc(url, "users", prop) ``` 在上述代码中,`prop`是一个包含`user`和`password`属性的`java.util.Properties`对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值