Dstream[Row] 資料批量匯入Mysql 並去重(大致為如果資料庫中有某行資料了,本次執行若有一行與資料庫中的那行相同,則不會再插入進去)
阿新 • • 發佈:2018-12-11
def Save2Mysql(stateDStream: DStream[Row]): Unit = { stateDStream.foreachRDD { rdd => { rdd.foreachPartition(partitionRecords => { /* var conn: Connection = null var ps: PreparedStatement = null val sql = "insert IGNORE into realtimehppro_autodiagnostic(systemid,subdevid,mo_subdevid,recordtime,leadRecordTime,errName,errReson) VALUES(?,?,?,?,?,?,?)" val driverClass="com.mysql.jdbc.Driver" Class.forName(driverClass) conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "") */ val pro = new Properties() val p2 = newDoLogic.getClass().getResourceAsStream("/db.properties") pro.load(p2) val url = pro.getProperty("url") val password = pro.getProperty("password") val username = pro.getProperty("user") val driverClass = pro.getProperty("driverClass") Class.forName(driverClass) val conn = DriverManager.getConnection(url, username, password) val sql = "insert IGNORE into realtimehppro_autodiagnostic(systemid,subdevid,mo_subdevid,recordtime,leadRecordTime,errName,errReson) VALUES(?,?,?,?,?,?,?)" val ps = conn.prepareStatement(sql) for (partitionRecord <- partitionRecords) { ps.setInt(1, partitionRecord.getInt(0).toInt) ps.setInt(2, partitionRecord.getInt(1).toInt) ps.setInt(3, partitionRecord.getInt(2).toInt) ps.setTimestamp(4, partitionRecord.getTimestamp(4)) ps.setTimestamp(5, partitionRecord.getTimestamp(5)) ps.setString(6, partitionRecord.getString(6)) ps.setString(7, partitionRecord.getString(7)) ps.addBatch() } try { ps.executeBatch() } catch { case e: Exception => println("插入資料失敗!") sys.exit(1) } finally { ps.close() conn.close() } } ) } } }
在工程的resource目錄下新建db.properties
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
user=root
password=
driverClass=com.mysql.jdbc.Driver
為了達到以上去重的目的:
一。在navicate中 對資料庫新建表 指定欄位之後,在儲存表之前,點索引,新增索引
1.指定索引名字
2.在欄位那裡選擇欄位(選擇的欄位 就是你想要按哪些欄位去重的欄位,即滿足這些欄位值相同的不同記錄行,只會插入1行到該表中)
3.在索引型別那裡 選擇Unique (表示只要唯一的一條記錄)
4.在索引方法那裡選擇BTREE
5.最後點儲存 指定表名,完成表的建立
二。 在java api 中 的sql 插入語句
記得在 insert 之後into之前 加上 IGNORE 來將當前結果中滿足主鍵或者索引的行 忽略,從而達到為資料庫表去重的目的。