import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
/**
* 事务
* @author Administrator
*
*/
public class TestTransaction {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
DriverManager.registerDriver(new OracleDriver());
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "scott";
String password = "tiger";
conn = DriverManager.getConnection(url, user, password);
//设置手动提交
conn.setAutoCommit(false);
String sql1 = "update emp set salary = salary - 100 where employee_id = 101";
pstmt1 = conn.prepareStatement(sql1);
pstmt1.executeUpdate();
String sql2 = "update emp set salary = salary + 100 where employee_id = 102";
pstmt2 = conn.prepareStatement(sql2);
pstmt2.executeUpdate();
conn.commit();//提交
} catch (Exception e) {
try {
conn.rollback();//回退事务
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
if(pstmt2 != null)
pstmt2.close();
if(pstmt1 != null)
pstmt1.close();
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Jdbc try catch
最新推荐文章于 2022-09-08 13:43:41 发布