JDBC事务的处理
准备数据
CREATE TABLE account (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(10),
balance DOUBLE
);
INSERT INTO account (NAME, balance) VALUES ('Jack', 1000), ('Rose', 1000);
API介绍
Connection接口中与事务有关的方法 |
说明 |
void setAutoCommit(boolean autoCommit) |
参数:true,关闭事务,false开启事务 |
void commit() |
提交事务 |
void rollback() |
回滚事务 |
开发步骤
l 使用事务的情况
1) 获取连接
2) 开启事务
3) 获取到PreparedStatement
4) 使用PreparedStatement执行两次更新操作
5) 正常情况下提交事务
6) 出现异常回滚事务
7) 最后关闭资源
public class DemoTransaction {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement("update account set balance = balance - 500 where name='jack'");
ps.executeUpdate();
System.out.println(100 / 0);
ps = conn.prepareStatement("update account set balance = balance + 500 where name='rose'");
ps.executeUpdate();
conn.commit();
System.out.println("转账成功");
} catch (Exception e) {
System.out.println("转账失败");
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
JdbcUtils.close(conn, ps);
}
}
}
public class JdbcUtils {
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final String URL = "jdbc:mysql://localhost:3306/day24";
private static final String DRIVER = "com.mysql.jdbc.Driver";
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void close(Connection conn, Statement stmt) {
if (stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
close(conn,stmt);
}
}