Class.forName(drv); Connection con=DriverManager.getConnection(url,user, password); con.setAutoCommit(false); ... PreparedStatement sta = null; ResultSet ret = null; while (...) { sta = con.prepareStatement(...); ret = sta.executeUpdate(); } con.commit();
String url="jdbc:oracle:thin:@172.28.9.232:1521:orcl";
String user="oltp";
String password="...oltp";
Class.forName(drv);
Connection con=DriverManager.getConnection(url,user, password);
con.setAutoCommit(false);
...
PreparedStatement sta = null;
ResultSet ret = null;
while (...) {
sta = con.prepareStatement(...);
ret = sta.executeUpdate();
}
...
con.commit(); //或者con.rollback();
String drv="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@172.28.9.232:1521:orcl";
String user="oltp";
String password="...oltp";
Class.forName(drv);
Connection con=DriverManager.getConnection(url,user, password);
con.setAutoCommit(false);
...
PreparedStatement sta = null;
ResultSet ret = null;
while (...) {
sta = con.prepareStatement(...);
ret = sta.executeUpdate();
}
con.commit();
}catch (Exception ex) {
con.rollback();
}
Statement stmt;
try
{
//get ur Connection & Statement conn.con.setAutoCommit(false); //do ur job conn.commit();
}
catch(Exception ex)
{
conn.rollback();
}
finally
{
conn.con.setAutoCommit(true); //release DB resource
try
{
....
}
catch(Exception ex){}
}
我看书找找去。
connection conn;
Statement stmt;
try{
//beginTrans();
...
conn.commit();
}
catch(Exception e){
...
throw e;
conn.rollback();
}
finally{
//freeConnection();
}
JDBC缺省方式是直接提交(Commit),
这在某些场合,例如同时更新若干条纪录,而且过程中须保证数据的一致性,
这时候,直接提交是显然不合适的
所以,用
conn.setAutoCommit(false);
宣告直接提交方式被禁止
事务完成之后,用
conn.commit();
方式显式提交,完成事务操作
而这个过程应当是在try区间内进行
若程序中产生Exception,则在catch区间捕获Exception,并且采用
conn.rollback();
回滚,即取消这次事务操作
最后,在finally区间关闭数据库连接,并用
conn.setAutoCommit(true);
重新宣告直接提交方式生效
为确保资源被正确关闭,建议关闭每个对像时分别作try、catch
处理事务
提交(在意外中回滚)