有一个方法
public void update(int state){
conn = ConnectionManager.getInstance().getConnection();
pst = conn.prepareStatement(sql1);--sql1是一个update sql语句
pst.setInt(1, state);
pst.execute();
--pst.cancel() 这个?
--pst.close() 这个? 还是都不用,直接执行下面的。怎么写保证不会丢东西呢。类似一个事物?难道用synchronized?
if(state==1) {
pst = conn.prepareStatement(sql2) --sql2是一个update sql语句
pst.setInt(1, state);
pst.execute();
--pst.cancel() 这个?
--pst.close() 这个? 还是都不用,直接执行下面的。怎么写保证不会丢东西呢。类似一个事物?难道用synchronized?
} else {
pst = conn.prepareStatement(sql3) --sql3是一个update sql语句
pst.setInt(1, state);
pst.execute();
--pst.cancel() 这个?
--pst.close() 这个? 还是都不用,直接执行下面的。怎么写保证不会丢东西呢。类似一个事物?难道用synchronized?
}
}
--请高手指教。如何写呢?
void close()
throws SQLException立即释放此 Statement 对象的数据库和 JDBC 资源,而不是等待该对象自动关闭时发生此操作。一般来说,使用完后立即释放资源是一个好习惯,这样可以避免对数据库资源的占用。
在已经关闭的 Statement 对象上调用 close 方法无效。 注:关闭 Statement 对象时,还将同时关闭其当前的 ResultSet 对象(如果有)。
抛出:
SQLException - 如果发生数据库访问错误
conn.setAutoCommit(false);//多个操作要开启事务
try
{
pst = conn.prepareStatement(sql1);
pst.setInt(1, state);
pst.execute();
if(state==1) {
pst = conn.prepareStatement(sql2) pst.setInt(1, state);
pst.execute();
} else {
pst = conn.prepareStatement(sql3)
pst.setInt(1, state);
pst.execute();
}
}
conn.commit();
}catch(Exception e){
System.out.println(e.getMessage());
conn.rollback();
}
finally{
conn.setAutoCommit(true);
pst.close();
conn.close();
}
如果业务上是同一个事务,建议手动提交,异常回滚。