您的位置:首页 > 其它

JDBC系列:(5)使用PreparedStatement进行批处理

2016-05-12 00:30 441 查看
批处理相关方法
序号方法作用
1void addBatch(String sql)添加批处理
2int[] executeBatch()执行批处理
3void clearBatch()清空批处理
package com.rk.db.e_batch;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.rk.db.utils.JDBCUtil;

public class Demo01
{
public static void main(String[] args)
{
Connection conn = null;
PreparedStatement pstmt = null;
try
{
// 获取连接
conn = JDBCUtil.getConnection();
//预编译的sql
String sql = "INSERT INTO T_Persons(UserName,Pwd) VALUES(?,?)";
// 创建stmt
pstmt = conn.prepareStatement(sql);
long startTime = System.currentTimeMillis();
for(int i=0;i<976;i++)
{
// 设置参数
pstmt.setString(1, "Lucy"+i);
pstmt.setString(2, "abc"+i);
// 添加批处理
pstmt.addBatch();
if(i%100==0)
{
// 批量执行
pstmt.executeBatch();
// 清空批处理
pstmt.clearBatch();
}
}
// 批量执行
pstmt.executeBatch();
// 清空批处理
pstmt.clearBatch();
long endTime = System.currentTimeMillis();
System.out.println("Total Time: " + (endTime - startTime));
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
JDBCUtil.close(conn, pstmt, null);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息