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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP