事务介绍
在JDBC中处理事务,都是通过Connection完成的。同一事务中所有的操作,都在使用同一个Connection对象。JDBC事务默认是开启的,并且默认是自动提交。
代码展示(未关连接)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static final String URL = "jdbc:mysql://localhost:3306/test";
public static final String USER = "root";
public static final String PASSWORD = "123456";
// 测试方法
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
// 开启事务
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
int rs = stmt.executeUpdate("DELETE FROM user WHERE name='qiang'");
if (rs > 0) {
System.out.println("更新成功!");
conn.rollback();
} else {
System.out.println("更新失败!");
conn.commit();
}
}
}