rdd和DF数据存入MYSQL

本文介绍使用Spark通过RDD和DataFrame两种方式批量将数据写入MySQL数据库的方法。具体包括使用RDD配合foreachPartition进行数据批量插入,以及利用DataFrame的write.jdbc方法进行数据更新,后者支持清空原有数据。

http://blog.youkuaiyun.com/dabokele/article/details/52802150

1.通过RDD函数批量存入数据

[java]  view plain  copy
  1. object RDDtoMysql {  
  2.   def myFun(iterator: Iterator[(String, Int)]): Unit = {  
  3.     var conn: Connection = null  
  4.     var ps: PreparedStatement = null  
  5.     val sql = "insert into sparktomysql(name, age) values (?, ?)"  
  6.     try {  
  7.          conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test_dw","test_dw""123456")  
  8.          iterator.foreach(data => {  
  9.           ps = conn.prepareStatement(sql)  
  10.           ps.setString(1, data._1)  
  11.           ps.setInt(2, data._2)  
  12.           ps.executeUpdate()  
  13.         }  
  14.       )  
  15.     } catch {  
  16.       case e: Exception => println("Mysql Exception")  
  17.     } finally {  
  18.       if (ps != null) {  
  19.         ps.close()  
  20.       }  
  21.       if (conn != null) {  
  22.         conn.close()  
  23.       }  
  24.     }  
  25.   }  
  26.   
  27.   def main(args: Array[String]) {  
  28.     val conf = new SparkConf().setAppName("RDDToMysql").setMaster("local")  
  29.     val sc = new SparkContext(conf)  
  30.     val data = sc.parallelize(List(("www"10), ("iteblog"20), ("com"30)))  
  31.     data.foreachPartition(myFun) //批量导入  
  32.   }  
  33. }  

2.DataFrame类操作mysql存入(适用于新建表和清空原来数据)

[java]  view plain  copy
  1. def main(args: Array[String]): Unit = {  
  2. val url = "jdbc:mysql://localhost:3306/spark?user=iteblog&password=iteblog"  
  3. val sc = new SparkContext  
  4. val sqlContext = new org.apache.spark.sql.SQLContext(sc)  
  5. val schema = StructType(  
  6. StructField("name", StringType) ::  
  7. StructField("age", IntegerType)  
  8.     :: Nil)  
  9. val data = sc.parallelize(List(("iteblog"30), ("iteblog"29),("com"40), ("bt"33), ("www"23))).map(item => Row.apply(item._1, item._2))  
  10. val df = sqlContext.createDataFrame(data, schema)  
  11.     df.insertIntoJDBC(url, "sparktomysql"true)//true代表删除原来数据进行插入  
  12.     sc.stop  
  13.   }  
此方法,在新版本 spark里面已经注销掉了。 .write.jdbc() 替代之了

definsertIntoJDBC(url: Stringtable: Stringoverwrite: Boolean)Unit

Save this DataFrame to a JDBC database at url under the table name table. Assumes the table already exists and has a compatible schema. If you pass truefor overwrite, it will TRUNCATE the table before performing the INSERTs.

The table must already exist on the database. It must have a schema that is compatible with the schema of this RDD; inserting the rows of the RDD in order via the simple statement INSERT INTO table VALUES (?, ?, ..., ?) should not fail.

Annotations
@deprecated
Deprecated

(Since version 1.4.0) Use write.jdbc(). This will be removed in Spark 2.0.


使用Scala语言基于Spark完成离线数据清洗、处理的过程可以分为以下几个步骤: 1. **数据加载**: 使用Spark的API从各种数据源(如HDFS、Hive、CSV、JSON等)中加载数据。 2. **数据合并**: 使用Spark的`union`、`join`等操作将多个数据集合并成一个数据集。 3. **数据去重**: 使用`distinct`或`dropDuplicates`方法去除重复数据。 4. **数据排序**: 使用`orderBy`或`sort`方法对数据进行排序。 5. **类型转换**: 使用`cast`方法将数据转换为所需的数据类型。 6. **数据存储**: 将处理后的数据存储MySQL、HBase、ClickHouse等存储系统中。 以下是一个简单的示例代码,展示了如何使用ScalaSpark完成上述步骤: ```scala import org.apache.spark.sql.{SparkSession, DataFrame} import org.apache.spark.sql.functions._ object DataProcessingJob { def main(args: Array[String]): Unit = { // 初始化SparkSession val spark = SparkSession.builder() .appName("Data Processing Job") .enableHiveSupport() .getOrCreate() // 数据加载 val df1: DataFrame = spark.read.format("csv").option("header", "true").load("hdfs://path/to/data1.csv") val df2: DataFrame = spark.read.format("csv").option("header", "true").load("hdfs://path/to/data2.csv") // 数据合并 val mergedDF = df1.union(df2) // 数据去重 val distinctDF = mergedDF.dropDuplicates() // 数据排序 val sortedDF = distinctDF.orderBy("column_name") // 类型转换 val convertedDF = sortedDF.withColumn("column_name", col("column_name").cast("desired_type")) // 数据存储MySQL convertedDF.write.format("jdbc") .option("url", "jdbc:mysql://hostname:port/database") .option("dbtable", "table_name") .option("user", "username") .option("password", "password") .mode(SaveMode.Append) .save() // 数据存储到HBase import spark.implicits._ convertedDF.rdd.map(row => { // 将DataFrame行转换为HBase的Put操作 }).saveAsHadoopDataset(conf) // 数据存储到ClickHouse convertedDF.write.format("jdbc") .option("url", "jdbc:clickhouse://hostname:port/database") .option("dbtable", "table_name") .option("user", "username") .option("password", "password") .mode(SaveMode.Append) .save() // 关闭SparkSession spark.stop() } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值