package practice
import java.sql.{ DriverManager, PreparedStatement}
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
object Practice02 {
def main(args: Array[String]): Unit = {
//spark本地模式运行
val conf = new SparkConf().setAppName("Practice02").setMaster("local")
val sc = new SparkContext(conf)
//创建rdd
val rdd: RDD[(Int, String)] = sc.parallelize(Array((120, "save"), (119, "fire")))
// 对每个分区执行 参数函数
rdd.foreach(it => {
//连接数据库的参数
val connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spark?characterEncoding=UTF-8",
"root", "15086479010")
//编写sql语句
val statement: PreparedStatement =connection.prepareStatement("insert into page_result02 values(?, ?)")
statement.setInt(1, it._1)
statement.setString(2, it._2)
statement.executeUpdate()
if (statement != null){
statement.close()
}
if (connection != null) {
connection.close()
}
})
}
}
insert into page_result02 values(?, ?)
这里是sql语句values(?,?)中的问好分别在下面被
statement.setInt(1, it._1)
statement.setString(2, it._2)
所定义了
运行结果