我正在使用glassfish 3.1.2和MySQL。运行我的应用程序时,我看到以下错误:
SEVERE: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
下面的是源代码:
public synchronized long generateKey(String sequenceName,int count) throws Exception {
PreparedStatement stmt=null;
ResultSet rset=null;
Connection db_conn = null;
StringBuffer sql = new StringBuffer();
long key=-1;
long maxKeyCount;
String sqlSeqNum="";
try {
// db_conn = Utility.getConnection("PASDataSource");
db_conn = Util.getConnection("ftpds");
sql.append("SELECT SEQ_NUM ");
sql.append("FROM SEQUENCE_GENERATOR ");
//SJ 2009.02.11, commented and added line below
//sql.append("WHERE sequence_name = ? ");
sql.append("WHERE SEQUENCE_NAME = ? for update");
System.out.println(sql + "::" + sequenceName);
stmt = db_conn.prepareStatement(sql.toString());
stmt.clearParameters();
stmt.setString(1,sequenceName);
rset = stmt.executeQuery ();
// Iterate through the result set
while(rset.next()) {
key = rset.getInt(1);
// Update the key
}
rset.close();
stmt.close();
stmt = null;
rset = null;
if(key != -1) {
if((key + count) > MAX_KEY_COUNT) {
// reset key count
// key = 1;
sqlSeqNum = "";
}
else
sqlSeqNum = " seq_num + ";
sql = new StringBuffer();
sql.append("UPDATE SEQUENCE_GENERATOR SET SEQ_NUM = " + sqlSeqNum + count );
sql.append(" WHERE SEQUENCE_NAME = ? ");
sql.append(" AND SEQ_NUM = ? ");
stmt = db_conn.prepareStatement(sql.toString());
stmt.clearParameters();
stmt.setString(1,sequenceName);
stmt.setLong(2,key);
if(stmt.executeUpdate() != 1) {
System.out.println(
":Not able to generate a new UNIQUE key for sequence :" + sequenceName);
throw new Exception("Not able to generate a new UNIQUE key for sequence :" + sequenceName );
}
return key;
}
return -1;
}
catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
finally {
if(db_conn!=null){
db_conn.close();
System.out.println("Inside finally, generateKey(String sequenceName,int count) method");
}}
}
完整堆栈跟踪显示错误发生在rset = stmt.executeQuery ();
。我第一次看到这个特殊的错误。如何解决这个问题?