package jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collection;
public class Test3 {
@Test
public void test() {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=PRC";
String username = "root";
String password = "";
Connection conn = null;
//加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库,代表数据库
conn = DriverManager.getConnection(url,username,password);
//通知数据库开启事务,false 开启
conn.setAutoCommit(false);
String sql = "update account set money = money-100 where name = ‘王五‘";
conn.prepareStatement(sql).executeUpdate();
//制作错误
//int i = 1/0;
String sql2 = "update account set money = money+200 where name = ‘张三‘";
conn.prepareStatement(sql2).executeUpdate();
conn.commit();//以上2条sql都执行成功了,就提交事务!
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
jdbc事务