一、工具类
连接工具类==> JDBC方式连接MySQL、Oracle、Hive、Spark等,通用工具类(Scala版),在此基础上添加批量插入的方法,代码如下:
def executeBatchUpdate(sqls: ArrayBuffer[String]){
var conn:Connection = null
var stat:Statement = null
try {
conn = getConnection()
stat = conn.createStatement()
for(sql<-sqls)
{
stat.addBatch(sql)
}
stat.executeBatch()
}catch{
case e : Exception => {
throw new Exception(e)
}
}finally{
if(stat!=null) {
stat.close()
}
if(conn!=null){
closeConnection()
}
}
}
二、使用示例
def bathInsertData(dataSet:Set[Map[String, Object]]):Unit = {
val arrayBuffer = new ArrayBuffer[String]()
var count = 1
//可以在配置文件中配置,此处为方便写死
val DB_BATCH_UPDATE_SIZE = 10
for (map <- dataSet) {
//业务处理逻辑
val insertSql = ""
arrayBuffer += insertSql
//batch insert
if (count % DB_BATCH_UPDATE_SIZE == 0){
JDBCUtil.executeBatchUpdate(arrayBuffer)
arrayBuffer.clear()
}
count = count + 1
}
//batch insert
JDBCUtil.executeBatchUpdate(arrayBuffer)
}
Just enjoy it!