为什么批处理一次只插入一条数据

valid303 2013-03-23 04:18:43
用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);
}
}
}
...全文
264 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ipnated 2013-03-23
  • 打赏
  • 举报
回复
引用 1 楼 fangmingshijie 的回复:
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();
				}
			 }
  • 打赏
  • 举报
回复
if(cnt%3==0){ st.executeBatch();//放到if外就行了。 con.commit(); st.clearBatch(); }

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧