public class JDBCDemo {
public static void main(String[] args) throws Exception {
// 0.需要将复制进来的jar包右键选择add ad library
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
// String url = "jdbc:mysql://127.0.0.1:3306/test230615?useSSL=false";
String url = "jdbc:mysql:///test230615?useSSL=false";
String username = "";
String password = "";
Connection connection = DriverManager.getConnection(url, username, password);
// 3.定义sql
String sql1 = "update account set money = 1000 where id = 1";
String sql2 = "update account set money = 1000 where id = 2";
// 4.获取执行sql的对象 statement
Statement statement = connection.createStatement();
// 开启事务
// ctrl+alt+t添加try catch将sql执行过程包裹起来
try {
// 开启事务
connection.setAutoCommit(false);
// 执行sql
int count1 = statement.executeUpdate(sql1);
System.out.println(count1);
int i =1/0; // 添加异常
int count2 = statement.executeUpdate(sql2);
System.out.println(count2);
// 提交事务
connection.commit();
} catch (Exception e) {
// 回滚事务
connection.rollback();
e.printStackTrace();
}
// 7.释放资源
connection.close();
statement.close();
}
JDBC使用connection进行事务管理
猜你喜欢
转载自blog.csdn.net/WuwuwuH_/article/details/131227232
今日推荐
周排行