事务开始与提交(以 Java 代码中的事务操作为例)
- Oracle(在 Java 中使用 JDBC 进行事务操作)
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement;public class OracleTransaction {public static void main(String[] args) {String url = "jdbc:oracle:thin:@//localhost:1521/ORCL";String user = "your_username";String password = "your_password";try {Connection connection = DriverManager.getConnection(url, user, password);connection.setAutoCommit(false); // 关闭自动提交,开启事务Statement statement = connection.createStatement();statement.executeUpdate("INSERT INTO employees (id, name, salary) VALUES (1, 'John', 5000.00)");statement.executeUpdate("INSERT INTO employees (id, name, salary) VALUES (2, 'Alice', 6000.00)");connection.commit(); // 提交事务connection.close();} catch (SQLException e) {e.printStackTrace();}} }
- MySQL(在 Java 中使用 JDBC 进行事务操作)
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement;public class MySQLTransaction {public static void main(String[] args) {String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false";String user = "your_username";String password = "your_username";try {Connection connection = DriverManager.getConnection(url, user, password);connection.setAutoCommit(false); // 关闭自动提交,开启事务Statement statement = connection.createStatement();statement.executeUpdate("INSERT INTO employees (id, name, salary) VALUES (1, 'John', 5000.00)");statement.executeUpdate("INSERT INTO employees (id, name, salary) VALUES (2, 'Alice', 6000.00)");connection.commit(); // 提交事务connection.close();} catch (SQLException e) {e.printStackTrace();}} }
虽然基本的事务操作逻辑相似(设置自动提交为
false
,执行多个操作后提交事务),但在数据库内部的事务管理机制方面,Oracle 和 MySQL 存在差异。例如,Oracle 在事务隔离级别、锁机制等方面更为复杂和强大。