import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import java.sql.PreparedStatement;
import com.qf.b_utils.DBUtils;
/**
* @author Zhouzilong
* @date 2019年8月8日
*/
public class BatchTest {
/**
* 多条不同语句
*/
@Test
public void batchTest1() {
Connection conn = null;
Statement st = null;
try {
conn = DBUtils.getConnection();
st = conn.createStatement();
st.addBatch("insert into t_user(name,password) values('ooo','123456')");
st.addBatch("update t_user set name = 'oo' where name = 'ooo'");
st.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtils.closeAll(st, conn);
}
}
/**
* 100条参数不同的相同语句
*/
@Test
public void batchTest2() {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("insert into t_user(name,password) values(?,?)");
for (int i = 1; i <= 100; i++) {
prst.setString(1, "zs" + i);
prst.setString(2, "12" + i);
prst.addBatch();
}
prst.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtils.closeAll(prst, conn);
}
}
/**
* 分批插入1000条参数不同的相同语句
*/
@Test
public void batchTest3() {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("insert into t_user(name,password) values(?,?)");
for (int i = 1; i <= 1000; i++) {
prst.setString(1, "zs" + i);
prst.setString(2, "12" + i);
prst.addBatch();
if (i % 100 == 0) {
// 每100条执行一次批处理
prst.executeBatch();
// 清空缓冲区
prst.clearBatch();
}
//后两句一般要加上
prst.executeBatch();
prst.clearBatch();
}
// 插入1000条只与数据库交互一次
prst.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(prst, conn);
}
}
}
数据库的简单批处理(增、删、改)
最新推荐文章于 2021-09-08 13:39:50 发布