首页 > 代码库 > 数据库的批处理

数据库的批处理

package cn.Pdispose;


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


import cn.paging.JdbcUtil;


//批处理
public class Dispose {
private static Connection conn = null;
private static Statement st = null;
private static PreparedStatement ps = null;
public static void testInsert(){
try {
conn = JdbcUtil.getConnection();
st = conn.createStatement();
String sql1 = "insert into t_name(id,name) values(1,‘jing‘)";
String sql2 = "insert into t_name(id,name) values(2,‘zhang‘)";
String sql3 = "delete from t_name where id = 1";
//addBatch()内部为一个list,加到list中
st.addBatch(sql1);
st.addBatch(sql2);
st.addBatch(sql3);
//元素师每条语句影响到的行数
int [] i = st.executeBatch();
for(int num : i){
System.out.println(num);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeJdbc(conn, null, ps);
}
}

//同时在一个表里边插入100条数据
//由于语句完全相同,只是参数不同,使用PreparedStatement
public static void testInsert_1(){
long date = System.currentTimeMillis();
try {
conn = JdbcUtil.getConnection();
String sql = "insert into t_name values(?,?)";
ps = conn.prepareStatement(sql);
for(int i=1;i<=100;i++){
ps.setInt(1, i);
ps.setString(2, "date---"+i);
//将一组参数添加到此 PreparedStatement 对象的批处理命令中。
ps.addBatch();
}
//将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组。
ps.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeJdbc(conn, null, ps);
}
System.out.println("用时:"+((System.currentTimeMillis()-date)/1000)+"秒");
}

//想数据库中插入10000条数据,并设置缓存区
public static void testInsert_2(){
//初始化一个时间
long time = System.currentTimeMillis();
try {
conn = JdbcUtil.getConnection();
String sql = "insert into t_name values(?,?)";
ps = conn.prepareStatement(sql);
for(int i=1;i<1000001;i++){
ps.setInt(1, i);
ps.setString(2, "date"+i);
ps.addBatch();
if(i%1000==0){
ps.executeBatch();
ps.clearBatch();//清空数据
}
}
ps.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeJdbc(conn, null, ps);
}

System.out.println("用时:"+((System.currentTimeMillis()-time)/1000)+"秒");
}


public static void main(String[] args) {
testInsert_2();
}
}