事务异常:
代码如下:
try {
con = BankSqlConnect.getconn();
con.setAutoCommit(false);
stmt = con.createStatement();
String sql = " ";
ResultSet rs;
days = getDays(accountid);
sql = "update account set last_time=getdate() "
+ "where account_num= " + accountid;
stmt.executeUpdate(sql);
mey = mey + balance;
mey = (float) (mey + mey * days * 0.003);
sql = "update account set balance = " + mey
+ "where account_num= " + accountid;
stmt.executeUpdate(sql);
result = "今天是: " + GetTime.getLongDate() + "已经成功存 " + mey
+ "钱,谢谢光临! ";
sql = "insert into message(account_num,message_context,message_time,message_class) values( ' "
+ accountid
+ " ', ' "
+ result
+ " ', ' "
+ GetTime.getLongDate() + " ',1) ";
stmt.executeUpdate(sql);
sql = "select customer_id from depositor where account_num= "
+ accountid;
rs = stmt.executeQuery(sql);
String a = " ";// 找出客户的ID
while (rs.next()) {
a = rs.getString( "customer_id ");
}
// 稍微加点信用值
sql = "update customer set customer_lever=customer_lever+ " + lv
+ " where customer_id like '% " + a + "% ' ";
stmt.executeUpdate(sql);
con.commit();
con.setAutoCommit(true);
return 1;
}
catch (Exception exp) {
exp.printStackTrace();
try{
if(con!=null)
{
con.rollback();
con.setAutoCommit(true);
}
}catch(SQLException ex){
ex.printStackTrace();
}
}finally{
try{
if(stmt!=null) stmt.close();
if(con!=null) con.close();
}catch(SQLException e2){
e2.printStackTrace();
}
}
代码在上:
错误提示:java.sql.SQLException: rollback() should not be called while in auto-commit mode.
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.rollback(ConnectionJDBC2.java:1893)
数据库是sql server 2000的
------解决方法--------------------------------------------------------
con.setAutoCommit(false);
改为
con.setAutoCommit(true);
------解决方法--------------------------------------------------------
这个异常应该不是抛出的第一个异常吧,你前面捕获异常的时候已经回滚了一次,设置autoCommit为ture了,第2次回滚的时候是AutoCommit模式,当然就抛异常了啊
------解决方法--------------------------------------------------------
con.commit();
con.setAutoCommit(true); //不要,去掉这句
con.rollback();
con.setAutoCommit(true);//不要,去掉这句
正确的格式是这样的
con.setAutoCommit(false);
try{
execute(sql1);
execute(sql);
con.commit();
}catch(Exception e){
con.rollback();
}