批量更新的问题

wumingmao1990 2012-07-18 03:57:41

public int BatchUpdate(String[] fields, String tableName, String[] conditions,String id) {
Connection conn = null;
PreparedStatement pst = null;
int count=0;
String sql="";
try {
conn = ConnectionSource.getConnection();
conn.setAutoCommit(false);
for(int i=0;i<conditions.length;i++){
sql="update "+tableName +" set "+fields[i]+" where "+id+"=?";
pst = conn.prepareStatement(sql);
pst.setObject(1, conditions[i]);
pst.addBatch();
}

int[]s= pst.executeBatch();
conn.commit();
count=s.length;
} catch (SQLException e) {
if(conn != null){
try {
conn.rollback();
conn.commit();
} catch (SQLException e1) {
loggerError.error(sql);
loggerError.error(e1);
e1.printStackTrace();
}
}
loggerError.error(e);
e.printStackTrace();
} finally {
ConnectionSource.releaseSource(null, pst, conn);
}
return count;
}

我不明白为什么只能更新最后一条记录,到底问题出在哪里看不出来,请大家帮忙看看。。谢谢了
...全文
99 4 打赏 收藏 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
达达KZT 2012-07-18
  • 打赏
  • 举报
回复
伸手党。
龙四 2012-07-18
  • 打赏
  • 举报
回复
你这种没法用PreparedStatment的addBatch来做
PreparedStatment#addBatch的前提是语句是一样的,只是set的参数不同
wumingmao1990 2012-07-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

pst = conn.prepareStatement(sql);

放到for循环前面去试试
[/Quote]

是这个原因。。但是我set fields[i] 该怎么办。。
龙四 2012-07-18
  • 打赏
  • 举报
回复
pst = conn.prepareStatement(sql);

放到for循环前面去试试

62,620

社区成员

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

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