为什么数据更新错误?(关键字:多线程,数据库更新不成功)
对数据库中的字段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;
}