我在写代码的时候发现,有错误,但有写数据还是更新了数据库这样就造成数据不完整,不知道jsp+win2000是怎么做到回滚的。我试过try是不行的,他只能屏蔽错误,但不能数据回滚。
try {
usercode.updateData("update tuser set re='145623' where id=75");
usercode.updateData("update tuser set re1='123' where id=75");
} catch(Exception e) {
}
这个是我自己做的例子,如果有try的时候没有提示错误,但更新了remark这个字段
没有try的时候,也更新了remark我的目的是,只要下面出现错误,更新的数据都回滚。
try {
usercode.updateData("update tuser set re='145623' where id=75");
usercode.updateData("update tuser set re1='123' where id=75");
} catch(Exception e) {
}
这个是我自己做的例子,如果有try的时候没有提示错误,但更新了remark这个字段
没有try的时候,也更新了remark我的目的是,只要下面出现错误,更新的数据都回滚。
.....事务执行....
connection.commit();
try {
usercode.updateData("update tuser set re='145623' where id=75");
usercode.updateData("update tuser set re1='123' where id=75");
Connection.commit();
} catch(Exception e) {
Connection.rollback();
}
只要两个sql中的任何一个出错,数据回滚
try和catch只是java的异常处理,和数据库根本没什么关系,你怎么把他们就这样连在一起了。
但两条sql语句任何一个出现异常进入catch得时候就必须回滚到
最开始,譬如说这么写:
try
{
m_conn.setAutoCommit(false);
usercode.updateData("update tuser set re='145623' where id=75");
usercode.updateData("update tuser set re1='123' where id=75");
}
catch (Exception e)
{
try
{
m_conn.rollback();
m_conn.setAutoCommit(true);
}
catch (Exception e2)
{
}
e.printStackTrace();
return false;
}
而想自己来设置这个回滚点得话,也可以设置个回滚点,这么写:
try
{
Savepoint save_point = null;
m_conn.setAutoCommit(false);
usercode.updateData("update tuser set re='145623' where id=75");
try
{
rollback_point = m_conn.setSavepoint("here");
}
catch (SQLException ex)
{
}
usercode.updateData("update tuser set re1='123' where id=75");
}
catch (Exception e)
{
try
{
m_conn.rollback(save_point);
m_conn.setAutoCommit(true);
}
catch (Exception e2)
{
}
e.printStackTrace();
return false;
}
这样设置得话,一旦发生异常,立刻回滚到你执行第一个sql语句得地方。