该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestJDBC {
private static String driver = “com.mysql.cj.jdbc.Driver”;
private static String url = “jdbc:mysql://localhost:3306/shiwentian?serverTimezone=UTC&&useSSL=false”;
private static String username = “root”;
private static String password = “123456aa”;
private static Connection conn = null;
public static void main(String[] args) throws SQLException {
testInsertInt1();
}
/**
* 就是一个普通的插入
*/
public static void normalInsert() throws Exception {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
PreparedStatement statement = conn.prepareStatement(“INSERT INTO student (name,cid) VALUES (‘shiwentian’,3)”);
statement.executeUpdate();
}
/**
* 带事务
*
* set false表示开启事务,执行多条语句, 默认是true,表示自动提交事物,执行1条语句,mysql中每一条语句默认情况下都是带事务的
*
* @throws SQLException
*/
public static void transcationInsert() throws SQLException {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
PreparedStatement statement1 = conn
.prepareStatement(“INSERT INTO student (name,cid) VALUES (‘transcation1’,1)”);
statement1.executeUpdate();
PreparedStatement statement2 = conn
.prepareStatement(“INSERT INTO student2 (name,cid) VALUES (‘transcation2’,2)”);
statement2.executeUpdate();
conn.commit();
} catch (Exception e) {
conn.rollback();// rollback之前必须setAutoCommit(false);否则rollback会报错
}
}
/**
* 自己测试事务挂起,难道只是重新创建一个conn这么简单么?我也不清楚,网上没有具体的代码事例关于挂起的
*/
public static void testInsertInt1() throws SQLException {
try {
Class.forName(driver);
Connection conn1 = DriverManager.getConnection(url, username, password);
conn1.setAutoCommit(false);
PreparedStatement statement1 = conn1
.prepareStatement(“INSERT INTO student2 (name,cid) VALUES (‘shiwentian1′,’3’)”);
statement1.executeUpdate();
// ==========
try {
Connection conn2 = DriverManager.getConnection(url, username, password);
conn2.setAutoCommit(false);
int i = 0;
int a = 3 / i;
PreparedStatement statement2 = conn2
.prepareStatement(“INSERT INTO student2 (name,cid) VALUES (‘shiwentian2′,’3’)”);
statement2.executeUpdate();
conn2.commit();
} catch (Exception e) {
System.out.println(“2异常”);
}
// ============
conn1.commit();
} catch (Exception e) {
conn.rollback();
}
}
}