每当我们使用executeQuery()
方法执行SQL语句时,它都会返回一个ResultSet对象,该对象保存SELECT查询返回的表格数据(通常)。
ResultSet对象包含一个指向当前行的游标/指针。最初,此光标位于第一行之前(默认位置)。
ResultSet接口的 isClosed() 方法用于确定当前ResultSet对象是否关闭。
rs.isclosed()
让我们使用CREATE语句在MySQL数据库中创建一个名称为tutorials_data 的表,如下所示-
CREATE TABLE tutorials_data ( tutorial_id INT, tutorial_title VARCHAR(100), tutorial_author VARCHAR(40), submission_date date, PRIMARY KEY (tutorial_id) );
现在,我们将使用INSERT语句在tutorials_data表中插入5条记录-
insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01')); insert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 ')); insert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01')); insert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01')); insert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06'));
接下来的JDBC程序与数据库建立连接,将上表的内容检索到一个ResultSet对象中,以显示其内容。
在这里,我们将ResultSet的可保存性设置为CLOSE_CURSORS_AT_COMMIT。因此,不久我们将关闭连接,ResultSet对象将被关闭。
我们正在验证是否使用该isClosed()
方法关闭了ResultSet对象。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_is_closed { public static void main(String args[]) throws Exception { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/mydb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建一个Statement对象 Statement stmt = con.createStatement(); //检索数据 ResultSet rs = stmt.executeQuery("select * from tutorials_data"); //将结果集设置为CLOSE_CURSORS_AT_COMMIT- con.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); System.out.println("ResultSet对象的内容:"); while(rs.next()) { System.out.print("ID: "+rs.getInt("tutorial_id")+", "); System.out.print("Title: "+rs.getString("tutorial_title")+", "); System.out.print("Author: "+rs.getString("tutorial_author")+", "); System.out.print("Submission date: "+rs.getDate("submission_date")); System.out.println(); } //关闭连接 con.close(); boolean bool = rs.isClosed(); if(bool) { System.out.println("ResultSet is closed"); } else { System.out.println("ResultSet is not closed"); } } }
输出结果
Connection established...... ResultSet对象的内容: ID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01 ID: 2, Title: JFreeCharts, Author: Satish kumar, Submission date: 2019-05-01 ID: 3, Title: JavaSprings, Author: Amit Tiwari, Submission date: 2019-03-01 ID: 4, Title: Android, Author: Sai Ram, Submission date: 2019-03-01 ID: 5, Title: Cassandra, Author: Pruthvi Raj, Submission date: 2019-04-06 ResultSet is closed