import java.sql.*; public class TransactionExample { public static void main(String[] args) { Connection connection = null; try { connection = getConnection(); connection.setAutoCommit(false); executeDatabaseOperations(connection); connection.commit(); } catch (SQLException e) { if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } } } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } private static Connection getConnection() throws SQLException { String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "123456"; return DriverManager.getConnection(url, username, password); } private static void executeDatabaseOperations(Connection connection) throws SQLException { Statement statement = connection.createStatement(); statement.executeUpdate("INSERT INTO users (name, age) VALUES ('John Doe', 30)"); statement.executeUpdate("DELETE FROM users WHERE age > 40"); statement.close(); } }


上一篇:
下一篇:
切换中文