日期:2014-05-20  浏览次数:20877 次

为什么批处理一次只插入一条数据
本帖最后由 valid303 于 2013-03-23 16:21:29 编辑
用c3p0 每3条批处理一次 结果只有中间那一条保存下来了 就是name那一列为 2、5、8、11...
我想要的是name那一列为 1、2、3、4... 

public class Tc3p0 {
public static void main(String[] args) {
Connection con = getConnection();Statement st=null;ResultSet rs=null; 
int cnt=0;
try {
con.setAutoCommit(false);
for(int i=0;i<100;i++){
String sql = "insert into users (name) values("+i+")";
st= con.createStatement();
st.addBatch(sql);
cnt++;
Thread.sleep(5000);
if(cnt%3==0){
st.executeBatch();
con.commit();
st.clearBatch();
}
 }
st.executeBatch();
con.commit();
st.clearBatch();
} catch (Exception e) {
e.printStackTrace();
}
}

private static ComboPooledDataSource ds = new ComboPooledDataSource();
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

------解决方案--------------------
if(cnt%3==0){
                    st.executeBatch();//放到if外就行了。
                    con.commit();
                    st.clearBatch();
                }
------解决方案--------------------
引用:
if(cnt%3==0){
                    st.executeBatch();//放到if外就行了。
                    con.commit();
                    st.clearBatch();
                }

我是想3条一起处理 放到if外面会不会导致效率和每条都自动提交一样
如果放外面的话 是不是也可以这样写 那为什么要有addBatch和executeBatch方法?
我只是想提高效率
			for(int i=0;i<100;i++){
String sql = "insert into users (name) values("+i+")";
st= con.createStatement();
st.executeUpdate(sql);
cnt++;
if(cnt%3==0){
con.commit();
}
 }