Java操作Oracle事务,以转账为例。
转账之前
package translate.commit;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class CommitRollback {public static void main(String[] args) {giao();}public static void giao() {Connection conn = null;PreparedStatement ps = null;PreparedStatement ps1 = null;try {conn = getConn();// jack 给 rose 转200 快String sql = "update stu set s_money = s_money - 200 where s_id = ?";// 预编译SQL语句。ps = conn.prepareStatement(sql);ps.setInt(1, 1);// 不让Java自动提交事务conn.setAutoCommit(false);int i = ps.executeUpdate();System.out.println(i>0 ? "转账成功" : "失败");// 模拟异常。System.out.println(1/0);sql = "update stu set s_money = s_money + 200 where s_id = ?";ps1 = conn.prepareStatement(sql);ps1.setInt(1, 2);conn.setAutoCommit(false);int i1 = ps1.executeUpdate();System.out.println(i1>0 ? "到账成功" : "失败");// 手动提交事务 如果没有异常,则可提交。conn.commit();} catch (Exception e) {try {// 程序由于算术错误 中断 所以要撤回提交。conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}e.printStackTrace();} finally {closeAll(conn, ps, null);try {if (ps1 != null)ps1.close();} catch (SQLException e) {e.printStackTrace();}}}public static Connection getConn() throws Exception {Class.forName("oracle.jdbc.OracleDriver");String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";Connection conn = DriverManager.getConnection(url, "scott", "scott");return conn;}public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) { try {if (rs != null)rs.close();if (ps != null)ps.close();if (conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}}
执行之后
SQL里面的事务介绍如下:
SQL事务