以下案例:
1、逐条执行10万次
2、分批执行将10万分成m批,每批n条,分多种分批方案来执行。
/**
* 批处理执行
*
* @param m 批次
* @param n 每批数量
* @throws Exception 异常时抛出
*/
public static void testInsertBatch(int m, int n) throws Exception {
init()//初始化环境
Long start = System.currentTimeMillis()
for (int i = 0i <mi++) {
//从池中获取连接
Connection conn = myBroker.getConnection()
Statement stmt = conn.createStatement()
for (int k = 0k <nk++) {
String sql = "\n" +
"insert into testdb.tuser \n" +
"\t(name, \n" +
"\tremark, \n" +
"\tcreatetime, \n" +
"\tupdatetime\n" +
"\t)\n" +
"\tvalues\n" +
"\t('" + RandomToolkit.generateString(12) + "', \n" +
"\t'" + RandomToolkit.generateString(24) + "', \n" +
"\tnow(), \n" +
"\tnow()\n" +
")"
//加入批处理
stmt.addBatch(sql)
}
stmt.executeBatch() //执行批处理
stmt.close()
myBroker.freeConnection(conn)//连接归池
}
Long end = System.currentTimeMillis()
System.out.println("批量执行" + m + "*" + n + "=" + m * n + "条Insert *** 作,共耗时:" + (end - start) / 1000f + "秒!")
}
java连接数据库时,往数据库一次添加多条数据,可以在DAO层,使用executeBatch()批量插入数据,如下代码:conn = DBToolkit.getConnection()
Statement stmt = conn.createStatement()
//连续添加多条SQL
stmt.addBatch("insert into testdb.book (kind, name) values ('java', 'java in aciton')")
stmt.addBatch("insert into testdb.book (kind, name) values ('c', 'c in aciton')")
//执行批量执行
stmt.executeBatch()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)