- JDBC 教程
- JDBC - 首页
- JDBC - 简介
- JDBC - SQL 语法
- JDBC - 环境
- JDBC - 示例代码
- JDBC - 驱动程序类型
- JDBC - 连接
- JDBC - 语句
- JDBC - 结果集
- JDBC - 数据类型
- JDBC - 事务
- JDBC - 异常
- JDBC - 批量处理
- JDBC - 存储过程
- JDBC - 数据流
- JDBC - RowSet
- JDBC - 复制数据库
- JDBC - ACID 属性
- JDBC - 连接池
- JDBC 示例
- JDBC - 创建数据库
- JDBC - 选择数据库
- JDBC - 删除数据库
- JDBC - 创建表
- JDBC - 删除表
- JDBC - 插入记录
- JDBC - 选择记录
- JDBC - 更新记录
- JDBC - 删除记录
- JDBC - WHERE 子句
- JDBC - LIKE 子句
- JDBC - 数据排序
- JDBC 有用资源
- JDBC - 问题和解答
- JDBC - 快速指南
- JDBC - 有用资源
- JDBC - 讨论
- 有用 - Java 教程
JDBC - 提交和回滚示例
以下是示例,它使用了commit 和rollback,这些在事务教程中进行了描述。
此示例代码是根据前面章节中完成的环境和数据库设置编写的。
使用 Commit 语句将插入的行持久化到表中的示例
在这个例子中,我们有六个静态字符串,包含数据库连接 URL、用户名、密码、SELECT 查询和两个 INSERT 查询。插入查询用于在 Employees 表中插入两条记录,而 Select 查询将用于获取所有员工。现在,使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。使用 setAutoCommit(false),我们将自动提交设置为 false,默认情况下为 true。连接准备就绪后,我们使用 connection.createStatement() 方法创建了一个 Statement 对象。在创建 Statement 对象时,我们使用 ResultSet 类型为 TYPE_SCROLL_INSENSITIVE 和 CONCUR_READ_ONLY。然后使用 statement.executeUpdate() 执行 INSERT 查询。现在,使用 commit() 方法,更改将持久化到数据库。
我们定义了一个 printResultSet() 方法,它以结果集作为参数,迭代它并打印结果集的所有记录。所有更改提交后,将调用 printResultSet() 方法以打印所有记录,以验证插入的记录是否可用。
将以下示例复制并粘贴到 JDBCCommitTransactionExample.java 中,编译并运行如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCCommitTransactionExample { static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT id, first, last, age FROM Employees"; static final String INSERT_QUERY = "INSERT INTO Employees (first, last, age) values('Rita', 'Tez', 20)"; static final String INSERT_QUERY_2 = "INSERT INTO Employees (first, last, age) values('Sita', 'Singh', 20)"; public static void printResultSet(ResultSet rs) throws SQLException{ // Ensure we start with first row rs.beforeFirst(); while(rs.next()){ // Display values System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } System.out.println(); } public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ // Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // Set auto commit as false. conn.setAutoCommit(false); // Execute a query to create statment with // required arguments for RS example. System.out.println("Creating statement..."); stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); // INSERT a row into Employees table System.out.println("Inserting one row...."); stmt.executeUpdate(INSERT_QUERY); // INSERT one more row into Employees table System.out.println("Inserting another row...."); stmt.executeUpdate(INSERT_QUERY_2); // Commit data here. System.out.println("Commiting data here...."); conn.commit(); // Now list all the available records. ResultSet rs = stmt.executeQuery(QUERY); System.out.println("List result set for reference...."); printResultSet(rs); // Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ se.printStackTrace(); // If there is an error then rollback the changes. System.out.println("Rolling back data here...."); try{ if(conn!=null) conn.rollback(); }catch(SQLException se2){ se2.printStackTrace(); } }catch(Exception e){ e.printStackTrace(); }finally{ // finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ se2.printStackTrace(); } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } }
输出
现在让我们编译上述示例,如下所示:
C:\>javac JDBCCommitTransactionExample.java C:\>
当您运行JDBCCommitTransactionExample时,它会产生以下结果:
C:\>java JDBCCommitTransactionExample Connecting to database... Creating statement... Inserting one row.... Inserting another row.... Commiting data here.... List result set for reference.... ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul ID: 6, Age: 20, First: Rita, Last: Tez ID: 7, Age: 20, First: Sita, Last: Singh C:\>
使用 Rollback 语句还原表中插入行的示例
在这个例子中,我们有六个静态字符串,包含数据库连接 URL、用户名、密码、SELECT 查询和两个 INSERT 查询。插入查询用于在 Employees 表中插入两条记录,而 Select 查询将用于获取所有员工。其中一个插入查询无效,因为 Employee1 表不存在。现在,使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。使用 setAutoCommit(false),我们将自动提交设置为 false,默认情况下为 true。连接准备就绪后,我们使用 connection.createStatement() 方法创建了一个 Statement 对象。在创建 Statement 对象时,我们使用 ResultSet 类型为 TYPE_SCROLL_INSENSITIVE 和 CONCUR_READ_ONLY。然后使用 statement.executeUpdate() 执行 INSERT 查询。
由于第二个 INSERT 查询无效,因此将引发 SQLException。我们处理了异常,并使用 rollback() 方法还原更改。
我们定义了一个 printResultSet() 方法,它以结果集作为参数,迭代它并打印结果集的所有记录。所有更改提交后,将调用 printResultSet() 方法以打印所有记录,以验证插入的记录是否已还原。
将以下示例复制并粘贴到 JDBCRollbackTransactionExample.java 中,编译并运行如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCRollbackTransactionExample { static final String MYSQL_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT"; static final String USER_NAME = "guest"; static final String PASSWORD = "guest123"; static final String INSERT_QUERY1 = "INSERT INTO Employees (first, last, age) values('Jeevan', 'Rao', 35)"; static final String INSERT_QUERY2 = "INSERT INTO Employees11 (first, last, age) values('Aditya', 'Chaube', 40)"; static final String SELECT_QUERY = "SELECT id, age, first, last FROM Employees"; public static void printResultSet(ResultSet rs) throws SQLException{ // Ensure we start with first row rs.beforeFirst(); while(rs.next()){ // Display values System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } System.out.println(); } public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ // Open database connection conn = DriverManager.getConnection(MYSQL_URL,USER_NAME,PASSWORD); System.out.println(" Connection established with TUTORIALSPOINT database."); conn.setAutoCommit(false); stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); System.out.println("Before inserting a row into Employees table"); stmt.executeUpdate(INSERT_QUERY1); System.out.println("Inserted a row into Employees table"); stmt.executeUpdate(INSERT_QUERY2); System.out.println("Before committing 2 inserts."); conn.commit(); System.out.println(" After committing 2 inserts."); rs = stmt.executeQuery(SELECT_QUERY); System.out.println("List ALL records of Employees table.."); printResultSet(rs); // Clean-up resources rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ se.printStackTrace(); System.out.println("If error has occured, discard changes"); try{ if(conn!=null) conn.rollback(); //Checking if records are in 'before-insert' state. rs = stmt.executeQuery(SELECT_QUERY); System.out.println("List ALL records of Employees table.."); printResultSet(rs); // Clean-up resources rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ se.printStackTrace(); System.out.println("If error has occured, discard changes"); try{ if(conn!=null) conn.rollback(); // Checking if records are in 'before-insert' state. rs = stmt.executeQuery(SELECT_QUERY); System.out.println("List ALL records of Employees table.."); printResultSet(rs); } catch(SQLException se2){ se2.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(rs != null){ rs.close(); } }catch(SQLException se1){ se1.printStackTrace(); } try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ se2.printStackTrace(); } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } } } }
输出
现在让我们编译上述示例,如下所示:
C:\>javac JDBCRollbackTransactionExample.java C:\>
当您运行JDBCRollbackTransactionExample时,它会产生以下结果:
C:\>java JDBCRollbackTransactionExample Connection established with TUTORIALSPOINT database. Before inserting a row into Employees table Inserted a row into Employees table java.sql.SQLSyntaxErrorException: Table 'tutorialspoint.employees11' doesn't exist at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:112) ... If error has occured, discard changes List ALL records of Employees table.. ID: 1, Age: 18, First: Zara, Last: Ali ID: 2, Age: 25, First: Mahnaz, Last: Fatma ID: 3, Age: 30, First: Zaid, Last: Khan ID: 4, Age: 28, First: Sumit, Last: Mittal ID: 7, Age: 20, First: Rita, Last: Tez ID: 8, Age: 20, First: Sita, Last: Singh C:\>