为什么数据更新错误?(关键字:多线程,数据库更新不成功)

ji_jian24 2004-08-30 11:14:23
对数据库中的字段A,我需要先将它的值加一,然后取出。
但这是一个多线程的东西,有N个线程针对这个字段A更新。
所以当我通过跟踪发现,有时update没有成功,system.out.println出来的数据经常会有重复的。
而且甚至跳号,即这次是211,下次print出来的结果却是213。甚至可能是214.
这是什么原因呢?




private String getNextSbbh(String id_swjg) throws SQLException {
int se = setNextSbbh(id_swjg);
if(se == 0){
try{
insertZdsbbh(id_swjg);
}catch(SQLException e){
e.printStackTrace();
}
}
String nextsbbh = "";
String strSqlSel = "select zdsbbh from s_sbbhzy (index pk_s_sbbhzy) where id_swjg='" + id_swjg + "'";
PreparedStatement prst = null;
ResultSet rs = null;
try{
prst = conn.prepareStatement(strSqlSel);
rs = prst.executeQuery();
while(rs.next()){
nextsbbh = StringUtil.trim(rs.getString("zdsbbh"));
System.out.println("------------- nextsbbh is:" + nextsbbh);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
closeResultSet(rs);
closePreparedStatement(prst);
}
return nextsbbh;
}

private int setNextSbbh(String id_swjg) throws SQLException {
int reSbbh = 0;
String nextsbbh = "";
String strSqlUpd = " update s_sbbhzy set zdsbbh=convert(char,convert(numeric(10,0),zdsbbh)+1) " +
" from s_sbbhzy (index pk_s_sbbhzy) " +
" where id_swjg='" + id_swjg + "'";
PreparedStatement prst = null;
try{
prst = conn.prepareStatement(strSqlUpd);
reSbbh = prst.executeUpdate();
System.out.println("reSbbh is : " + reSbbh);
}catch(SQLException e){
e.printStackTrace();
}finally{
closePreparedStatement(prst);
}
return reSbbh;
}
...全文
247 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
射天狼 2004-08-30
  • 打赏
  • 举报
回复
private synchronized String getNextSbbh(String id_swjg) throws SQLException
private synchronized int setNextSbbh(String id_swjg) throws SQLException

同步这两个方法就可以!
Lulq21cn 2004-08-30
  • 打赏
  • 举报
回复
其实处理序号自动加一的问题我以为最好就是放在数据库的触发器中自动运行,当然这样就损失了一定的通用性,如果有的数据库不支持触发器就没法这样做。
drugon 2004-08-30
  • 打赏
  • 举报
回复
多线程之间你有没有让它们同步进行呀,象这种资源共享的时候就要保证一个线程在修改时其它线程是不能读的,不然的话就有可能读出的数据是脏数据。也就是说最好你能把这个字段加锁,保护好。基本的线程同步问题。
qqbz 2004-08-30
  • 打赏
  • 举报
回复
同步这两个方法。
LittleLandlord 2004-08-30
  • 打赏
  • 举报
回复
应该是数据库更新速度慢的原因
LittleLandlord 2004-08-30
  • 打赏
  • 举报
回复
你更新完数据库,延时一段时间试试,我以前好象也碰到过
ji_jian24 2004-08-30
  • 打赏
  • 举报
回复
to 楼上,
   我加了,结果依旧。

62,623

社区成员

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

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