Java Connection setHoldability() 方法及示例


ResultSet 的可保持性決定了當使用 Connection 介面的 commit() 方法提交事務(包含該遊標/ResultSet 物件)時,ResultSet 物件(遊標)是否應該關閉或保持開啟狀態。

**Connection** 介面的 **setHoldability()** 方法用於將此連線(使用此連線建立)中 ResultSet 物件的可保持性設定為所需值。

引數

此方法接受一個整數作為引數,表示要設定的 ResultSet 可保持性值。ResultSet 介面提供兩個值來指定 ResultSet 的可保持性:

  • **CLOSE_CURSORS_AT_COMMIT:** 如果 ResultSet 物件的可保持性設定為該值,則每當使用 Connection 介面的 commit() 方法提交/儲存事務時,當前事務中建立的(已開啟的)ResultSet 物件都將被關閉。

  • **HOLD_CURSORS_OVER_COMMIT:** 如果 ResultSet 物件的可保持性設定為該值,則每當使用 Connection 介面的 commit() 方法提交/儲存事務時,當前事務中建立的(已開啟的)ResultSet 物件都將保持開啟狀態。

要更改/設定所需的可保持性值:

使用 DriverManager 類的 registerDriver() 方法註冊驅動程式:

//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

使用 DriverManager 類的 getConnection() 方法獲取連線:

//Getting the connection
String url = "jdbc:mysql:///mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");

使用 Connection 介面的 setHoldability() 方法將 ResultSet 可保持性設定為所需的值:

con.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);

示例

下面的 JDBC 程式建立與資料庫的連線,並將可保持性值設定為 CLOSE_CURSORS_AT_COMMIT。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Connection_setHoldability {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql:///mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Setting the auto commit false
      con.setAutoCommit(false);
      //Setting the holdability to CLOSE_CURSORS_AT_COMMIT
      con.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
      System.out.println("ResultSet holdability value has been changed to "+con.getHoldability());
   }
}

輸出

Connection established......
ResultSet object is open

更新於:2019年7月30日

343 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.