发生异常时重新执行数据库更新查询

时间:2013-05-15 11:20:59

标签: java mysql sql

我想在SQLException发生的时候重新执行查询,有时我得到了

的异常
SQLException occurred... com.mysql.jdbc.exceptions.jdbc4.
MySQLTransactionRollbackExceptionDeadlock
found when trying to get lock; try restarting transaction

我的代码如下。数据库是MySQL InnoDB ..请建议......

  String sqlquery = "UPDATE tbl_users SET abill=?" 
                                 + " WHERE uid=? AND sms='2'"; 

     PreparedStatement preStatement=null;
      try{
         con.setAutoCommit(false);
        preStatement=con.prepareStatement(sqlquery);
        preStatement.setString(1,billpush);
        preStatement.setString(2,uid);
        preStatement.executeUpdate();
        con.commit();
       }

     catch(SQLException sE)
     {
       log.error("SQLException occurred... "+sE);
         con.rollback();
     }
      finally {
if (preStatement != null) {
preStatement.close();
    }        
            }

2 个答案:

答案 0 :(得分:1)

UPDATE tbl_users SET abill=billpush, asms ='2' WHERE uid='uid' AND sms='2' and asms<>'2'

这将防止死锁只是在asms&lt;&gt;'2'的末尾添加一个条件。希望这能解决问题。

答案 1 :(得分:0)

在危险操作后,只需将标记设置为true

bool ok = false;

while (!ok) {
    ok = false;
    try {
        doSomethingFishy();
        ok = true;
    }
    catch(Exception e) {
        dealWithError(); // perhaps wait for a short while and increment a "retry" counter
    }
}