

示例代码:
package com.fdw.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestJdbc3 {
public static void main(String[] args) {
//配置信息
String url ="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
Connection connection =null;
//1.加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接数据库
connection = DriverManager.getConnection(url, username, password);
//开启事务
connection.setAutoCommit(false);
//3.编写SQl
String sql1 = "update user set name = '哇哈哈哈1' where id=1";
connection.prepareStatement(sql1).executeUpdate();
//制造错误
// int i =1/0;
String sql2 = "update user set name = '哈哈哈哇' where id=2";
connection.prepareStatement(sql2).executeUpdate();
//提交
connection.commit();
System.out.println("执行完毕!");
} catch (Exception e) {
try {
//回滚
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
版权声明:本文为weixin_44853310原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。