重点的三个代码
1./** 将事务设置为手动提交,即开启了事务 /
conn.setAutoCommit(false);
2. /* 以上程序执行完成,事务结束 /
conn.commit();
3. /* 回滚事务 */
conn.rollback();
package com.Jdbc;
import java.sql.*;
/**
* 事务处理
*/
public class test08 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sm","root","root");
/** 将事务设置为手动提交,即开启了事务 */
conn.setAutoCommit(false);
//3.获取数据库执行对象
String sql = "update smbms_user set userCode = ? where id = ?";
ps = conn.prepareStatement(sql); //预编译
//4.执行sql语句,传值
ps.setString(1,"300");
ps.setInt(2,2);
int i = ps.executeUpdate();
//传值
ps.setString(1,"700");
ps.setInt(2,5);
i += ps.executeUpdate();
System.out.println(i == 2 ? "转账成功!":"转账失败!");
int m = 1/0; // <==异常发生!
//5.返回结果集
/** 以上程序执行完成,事务结束 */
conn.commit();
}catch(Exception ex){
if (conn!=null) {
try {
/** 回滚事务 */
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
ex.printStackTrace();
}finally{
//6.释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}