Java ResultSet interface is a part of the java.sql package. It is one of the core components of the JDBC Framework. ResultSet Object is used to access query results retrieved from the relational databases.

Java ResultSet接口是java.sql包的一部分。 它是JDBC框架的核心组件之一。 ResultSet对象用于访问从关系数据库检索的查询结果。

ResultSet maintains cursor/pointer which points to a single row of the query results. Using navigational and getter methods provided by ResultSet, we can iterate and access database records one by one. ResultSet can also be used to update data.

ResultSet维护指向查询结果的单行的光标/指针。 使用ResultSet提供的导航和获取方法,我们可以一个一个地迭代和访问数据库记录。 ResultSet也可以用于更新数据。

Java ResultSet层次结构 (Java ResultSet Hierarchy)

Java ResultSet Class Hierarchy
Java ResultSet类层次结构

The above diagram shows the place of ResultSet in the JDBC Framework. ResultSet can be obtained by executing SQL Query using Statement, PreparedStatement or CallableStatement.

上图显示了ResultSet在JDBC Framework中的位置。 通过使用StatementPreparedStatementCallableStatement执行SQL查询可以获得ResultSet

AutoCloseable, Wrapper are super interfaces of ResultSet.  Now we will see how to work with ResultSet in our Java programs.

AutoCloseableWrapper是ResultSet的超级接口。 现在,我们将看到如何在Java程序中使用ResultSet。

ResultSet示例 (ResultSet Example)

We will be using MySQL for our example purpose. Use below DB script to create a database and table along with some records.

我们将使用MySQL作为示例。 使用下面的DB脚本来创建数据库和表以及一些记录。


create database empdb;use empdb;create table tblemployee (empid integer primary key, firstname varchar(32), lastname varchar(32), dob date);insert into tblemployee values  (1, 'Mike', 'Davis',' 1998-11-11');
insert into tblemployee values  (2, 'Josh', 'Martin', '1988-10-22');
insert into tblemployee values  (3, 'Ricky', 'Smith', '1999-05-11');

Let’s have look at the below example program to fetch the records from the table and print them on the console. Please make sure you have the MySQL JDBC driver in the project classpath.

让我们看下面的示例程序,从表中获取记录并将其打印在控制台上。 请确保在项目类路径中有MySQL JDBC驱动程序。


package com.journaldev.examples;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;/*** Java Resultset Example of Retrieving records.* * @author pankaj**/public class ResultSetDemo {public static void main(String[] args) {String query = "select empid, firstname, lastname, dob from tblemployee";Connection conn = null;Statement stmt = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/empdb", "root", "root");stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(query);while (rs.next()) {Integer empId = rs.getInt(1);String firstName = rs.getString(2);String lastName = rs.getString(3);Date dob = rs.getDate(4);System.out.println("empId:" + empId);System.out.println("firstName:" + firstName);System.out.println("lastName:" + lastName);System.out.println("dob:" + dob);System.out.println("");}rs.close();} catch (Exception e) {e.printStackTrace();} finally {try {stmt.close();conn.close();} catch (Exception e) {}}}
}

Output:

输出:


empId:1
firstName:Mike
lastName:Davis
dob:1998-11-11empId:2
firstName:Josh
lastName:Martin
dob:1988-10-22empId:3
firstName:Ricky
lastName:Smith
dob:1999-05-11

Explanation:

说明

  • ResultSet is obtained by calling the executeQuery method on Statement instance. Initially, the cursor of ResultSet points to the position before the first row.通过调用Statement实例上的executeQuery方法获得ResultSet。 最初,ResultSet的光标指向第一行之前的位置。
  • The method next of ResultSet moves the cursor to the next row. It returns true if there is further row otherwise it returns false.ResultSet的next方法将光标移动到下一行。 如果还有其他行,则返回true,否则返回false。
  • We can obtain data from ResultSet using getter methods provided by it. e.g.  getInt(),  getString(),  getDate()我们可以使用它提供的getter方法从ResultSet中获取数据。 例如getInt(),getString(),getDate()
  • All the getter methods have two variants. 1st variant takes column index as Parameter and 2nd variant accepts column name as Parameter.所有的getter方法都有两个变体。 第一个变量将列索引作为参数, 第二个变量将列名称作为参数。
  • Finally, we need to call close method on ResultSet instance so that all resources are cleaned up properly.最后,我们需要在ResultSet实例上调用close方法,以便正确清理所有资源。

结果集类型和并发 (ResultSet Types & Concurrency)

We can specify type and concurrency of  ResultSet while creating an instance of Statement, PreparedStatement or CallableStatement.

在创建Statement, PreparedStatement或CallableStatement的实例时,我们可以指定ResultSet的类型和并发性。

statement.createStatement(int resultSetType, int resultSetConcurrency)

statement.createStatement(int resultSetType,int resultSetConcurrency)

结果集类型 (ResultSet Types)

1)仅转发(ResultSet。TYPE_FORWARD_ONLY (1) Forward Only (ResultSet.TYPE_FORWARD_ONLY))

This type of ResultSet instance can move only in the forward direction from the first row to the last row. ResultSet can be moved forward one row by calling the next() method. We can obtain this type of ResultSet while creating Instance of Statement, PreparedStatement or CallableStatement.

这种类型的ResultSet实例只能从第一行到最后一行向前移动。 可以通过调用next()方法将ResultSet向前移动一行。 在创建Statement,PreparedStatement或CallableStatement的实例时,我们可以获取这种类型的ResultSet。


Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from tbluser");

2)滚动不敏感(结果集。TYPE_SCROLL_INSENSITIVE) (2) Scroll Insensitive (ResultSet.TYPE_SCROLL_INSENSITIVE))

Scroll Insensitive ResultSet can scroll in both forward and backward directions. It can also be scrolled to an absolute position by calling the absolute() method. But it is not sensitive to data changes. It will only have data when the query was executed and ResultSet was obtained. It will not reflect the changes made to data after it was obtained.

滚动不敏感ResultSet可以向前和向后滚动。 也可以通过调用absolute()方法将其滚动到绝对位置。 但是它对数据更改不敏感。 它仅在执行查询并获得ResultSet时才具有数据。 它不会反映获得数据后对数据所做的更改。


Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,         ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from tbluser");

3)敏感滚动(ResultSet。TYPE_SCROLL_SENSITIVE (3) Scroll Sensitive (ResultSet.TYPE_SCROLL_SENSITIVE))

Scroll Sensitive ResultSet can scroll in both forward and backward directions. It can also be scrolled to an absolute position by calling the absolute() method. But it is sensitive to data changes. It will reflect the changes made to data while it is open.

滚动敏感结果集可以向前和向后滚动。 也可以通过调用absolute()方法将其滚动到绝对位置。 但是它对数据更改很敏感。 它会反映打开时对数据所做的更改。


Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,       ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from tbluser");

ResultSet 并发 (ResultSet Concurrency)

1)只读(ResultSet。CONCUR_READ_ONLY (1) Read Only (ResultSet.CONCUR_READ_ONLY))

It is the default concurrency model.  We can only perform Read-Only operations on ResultSet Instance. No update Operations are allowed.

它是默认的并发模型。 我们只能对ResultSet实例执行只读操作。 不允许任何更新操作。

2)可更新(ResultSet。CONCUR_UPDATABLE (2) Updatable (ResultSet.CONCUR_UPDATABLE))

In this case, we can perform update operations on ResultSet instance.

在这种情况下,我们可以对ResultSet实例执行更新操作。

结果集方法 (ResultSet Methods)

We can divide ResultSet methods into the following categories.

我们可以将ResultSet方法分为以下几类。

  • Navigational Methods导航方法
  • Getter/Reader Methods读/写方法
  • Setter/Updater Methods设置器/更新器方法
  • Miscellaneous Methods – close() and getMetaData()其他方法 – close()和getMetaData()

1. ResultSet导航方法 (1. ResultSet Navigational Methods)

  • boolean absolute(int row) throws SQLException: This method moves ResultSet cursor to the specified row and returns true if the operation is successful.boolean absolute( int row) 引发 SQLException 此方法将ResultSet游标移动到指定的行,如果操作成功,则返回true。
  • void afterLast() throws SQLException: This method moves ResultSet cursor to the position after the last row.afterLast() 引发 SQLException 无效 此方法将ResultSet光标移动到最后一行之后的位置。
  • void beforeFirst() throws SQLException: This method moves ResultSet cursor to the position before the first row.void beforeFirst() 抛出 SQLException 此方法将ResultSet光标移动到第一行之前的位置。
  • boolean first() throws SQLException: This method moves ResultSet cursor to the first row.boolean first() 引发 SQLException:此方法将ResultSet光标移到第一行。
  • boolean last() throws SQLException: This method moves ResultSet cursor to the last row.boolean last() 引发 SQLException:此方法将ResultSet光标移到最后一行。
  • boolean next() throws SQLException: This method moves ResultSet cursor to the next row.boolean next() 引发 SQLException:此方法将ResultSet光标移到下一行。
  • boolean previous() throws SQLException: This method moves ResultSet cursor to the previous row.boolean previous() 抛出 SQLException:此方法将ResultSet光标移到上一行。

package com.journaldev.examples;
import java.sql.*;/*** Java Resultset Example using navigational methods.* * @author pankaj**/
public class ResultSetDemo {public static void main(String[] args) {String query = "select empid, firstname, lastname, dob from tblemployee";Connection conn = null;Statement stmt = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/empdb", "root", "root");stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);ResultSet rs = stmt.executeQuery(query);System.out.println("All the rows of table=>");while (rs.next()) { // Go to next row by calling next() methoddisplayData(rs);}System.out.println("Now go directly to 2nd row=>");rs.absolute(2); // Go directly to 2nd rowdisplayData(rs);System.out.println("Now go to Previous row=>");rs.previous(); // Go to 1st row which is previous of 2nd rowdisplayData(rs);rs.close();} catch (Exception e) {e.printStackTrace();} finally {try {stmt.close();conn.close();} catch (Exception e) {}}}public static void displayData(ResultSet rs) throws SQLException {System.out.println("empId:" + rs.getInt(1));System.out.println("firstName:" + rs.getString(2));System.out.println("lastName:" + rs.getString(3));System.out.println("dob:" + rs.getDate(4));System.out.println("");}
}

Output:

输出:


All the rows of table=>
empId:1
firstName:Mike
lastName:Davis
dob:1998-11-11empId:2
firstName:Josh
lastName:Martin
dob:1988-10-22empId:3
firstName:Ricky
lastName:Smith
dob:1999-05-11Now go directly to 2nd row=>
empId:2
firstName:Josh
lastName:Martin
dob:1988-10-22Now go to Previous row=>
empId:1
firstName:Mike
lastName:Davis
dob:1998-11-11

2. ResultSet的Getter / Reader方法 (2. ResultSet Getter/Reader Methods)

  • int getInt(int columnIndex) throws SQLException: This method returns value of specified columnIndex as int.int getInt( int columnIndex) 引发 SQLException:此方法将指定columnIndex的值作为int返回。
  • long getLong(int columnIndex) throws SQLException: This method returns value of specified columnIndex as longlong getLong( int columnIndex) 抛出 SQLException:该方法返回指定columnIndex的值, 只要long
  • String getString(int columnIndex) throws SQLException: This method returns value of specified columnIndex as StringString getString( int columnIndex) 引发 SQLException:此方法将指定的columnIndex的值作为String返回
  • java.sql.Date getDate(int columnIndex) throws SQLException: This method returns value of specified columnIndex as java.sql.Datejava.sql.Date getDate( int columnIndex) 抛出 SQLException:此方法将指定columnIndex的值作为java.sql.Date返回
  • int getInt(String columnLabel) throws SQLException: This method returns value of specified column name as int.int getInt(String columnLabel) 抛出 SQLException:此方法返回指定列名的值作为int
  • long getLong(String columnLabel) throws SQLException: This method returns value of specified column name as long.long getLong(String columnLabel) 抛出 SQLException:此方法返回指定列名的值long
  • String getString(String columnLabel) throws SQLException: This method returns the value of the specified column name as String.String getString(String columnLabel) 抛出 SQLException:此方法以String形式返回指定列名称的值。
  • java.sql.Date getDate(String columnLabel) throws SQLException: This method returns the value of the specified column name as java.sql.Date.java.sql.Date getDate(String columnLabel)引发SQLException:此方法以java.sql.Date的形式返回指定列名称的值。
  • ResultSet contains getter methods that return other primitive datatypes like boolean, float and double. It also has methods to obtain array and binary data from the database.ResultSet包含getter方法,这些方法返回其他原始数据类型,例如boolean,float和double。 它还具有从数据库中获取数组和二进制数据的方法。

3. ResultSet 设置器/更新器方法 (3. ResultSet Setter/Updater Methods)

  • void updateInt(int columnIndex, int x) throws SQLException: This method updates the value of specified column of current row with int value.void updateInt( int columnIndex, int x) 引发 SQLException:此方法使用int值更新当前行的指定列的值。
  • void updateLong(int columnIndex, long x) throws SQLException: This method updates the value of the specified column of the current row with long value.void updateLong( int columnIndex, long x) 引发 SQLException:此方法使用long值更新当前行的指定列的值。
  • void updateString(int columnIndex, String x) throws SQLException: This method updates the value of the specified column of the current row with a String value.void updateString(int columnIndex,String x)引发SQLException:此方法使用String更新当前行的指定列的值 值。
  • void updateDate(int columnIndex, java.sql.Date x) throws SQLException: This method updates the value of specified column of current row with java.sql.Date value.void updateDate( int columnIndex,java.sql.Date x) 引发 SQLException:此方法使用java.sql.Date更新当前行的指定列的值 值。
  • void updateInt(String columnLabel, int x) throws SQLException: This method updates the value of the specified column label of the current row with int value.void updateInt(String columnLabel,int x)引发SQLException:此方法使用int值更新当前行的指定列标签的值。
  • void updateLong(String columnLabel, long x) throws SQLException: This method updates the value of the specified column label of the current row with long value.void updateLong(String columnLabel,long x)引发SQLException:此方法使用long值更新当前行的指定列标签的值。
  • void updateString(String columnLabel, String x) throws SQLException: This method updates the value of the specified column label of the current row with a String value.void updateString(String columnLabel,String x)引发SQLException:此方法使用String更新当前行的指定列标签的值 值。
  • void updateDate(String columnLabel, java.sql.Date x) throws SQLException: This method updates the value of specified columnLabel of current row with java.sql.Date value.void updateDate(String columnLabel,java.sql.Date x) 引发 SQLException:此方法使用java.sql.Date值更新当前行的指定columnLabel的值。

Note: Setter/Updater Methods doesn’t directly update database values. Database values will be inserted/updated after calling the insertRow or updateRow method.

注意:设置器/更新器方法不会直接更新数据库值。 调用insertRow或updateRow方法后,将插入/更新数据库值


package com.journaldev.examples;
import java.sql.*;/*** Java Resultset Example using updater methods.* * @author pankaj**/public class ResultSetUpdateDemo {public static void main(String[] args) {String query = "select empid, firstname, lastname, dob from tblemployee";Connection conn = null;Statement stmt = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/empdb", "root", "root");stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);ResultSet rs = stmt.executeQuery(query);System.out.println("Now go directly to 2nd row for Update");if (rs.absolute(2)) { // Go directly to 2nd rowSystem.out.println("Existing Name:" + rs.getString("firstName"));rs.updateString("firstname", "Tyson");rs.updateRow();}rs.beforeFirst(); // go to startSystem.out.println("All the rows of table=>");while (rs.next()) { // Go to next row by calling next() methoddisplayData(rs);}rs.close();} catch (Exception e) {e.printStackTrace();} finally {try {stmt.close();conn.close();} catch (Exception e) {}}}public static void displayData(ResultSet rs) throws SQLException {System.out.println("empId:" + rs.getInt(1));System.out.println("firstName:" + rs.getString(2));System.out.println("lastName:" + rs.getString(3));System.out.println("dob:" + rs.getDate(4));System.out.println("");}
}

Output:

输出:


Now go directly to 2nd row for Update
Existing Name:Josh
All the rows of table=>
empId:1
firstName:Mike
lastName:Davis
dob:1998-11-11empId:2
firstName:Tyson
lastName:Martin
dob:1988-10-22empId:3
firstName:Ricky
lastName:Smith
dob:1999-05-11

4. ResultSet其他方法 (4. ResultSet Miscellaneous Methods)

  • void close() throws SQLException: This method frees up resources associated with ResultSet Instance. It must be called otherwise it will result in resource leakage.void close() 抛出 SQLException 此方法释放与ResultSet实例关联的资源。 必须调用它,否则将导致资源泄漏。
  • ResultSetMetaData getMetaData() throws SQLException: This method returns ResultSetMetaData instance. It gives information about the type and property of columns of the query output.ResultSetMetaData getMetaData() 引发 SQLException:此方法返回ResultSetMetaData实例。 它提供有关查询输出的列的类型和属性的信息。

Reference: Java doc

参考 : Java文档

翻译自: https://www.journaldev.com/34720/java-resultset

Java ResultSet教程相关推荐

  1. java培训教程分享:Java中怎样将数据对象序列化和反序列化?

    本期为大家介绍的java培训教程是关于"Java中怎样将数据对象序列化和反序列化?"的内容,相信大家都知道,程序在运行过程中,可能需要将一些数据永久地保存到磁盘上,而数据在Java ...

  2. java培训教程分享:Java编写软件代码自动提示功能

    本期的java培训教程分享主要是介绍的java编写软件代码的一个自动提示功能,很多零基础和初学java的同学们对这一块还不是很了解,Eclipse for android 实现代码自动提示智能提示功能 ...

  3. java培训教程分享:Java中用户如何自定义异常?

    我们在学习java技术的时候应该有了解过,在java中是定义了很多的异常类的,虽然这些大量异常类可以帮助我们描述编程时出现的大部分异常情况,但是在程序开发中有时可能需要描述程序中特有的异常情况,例如在 ...

  4. java培训教程:什么是匿名内部类?怎样创建匿名内部类?

    本期java教程要为大家分享的是关于java中的匿名内部类,相信很多同学在学java技术的时候有了解过,下面我们就来详细的看一下. java培训教程:什么是匿名内部类?怎样创建匿名内部类?匿名内部类是 ...

  5. Java培训教程:”==“和 equals 方法究竟有什么区别?

    在学习java技术过程中,我们会接触到一些变量值的相关知识,本期小编为大家介绍的教程就是关于"=="和 equals 方法究竟有什么区别?来看看下面的详细介绍. Java培训教程: ...

  6. [转] Java快速教程

    [转] Java快速教程 转自:Vamei的Java快速教程 2015-07-03 安装环境 Step 1: Eclipse JDK 下载.安装.配置 (download.install.deploy ...

  7. Java快速教程--vamei 学习笔记(基础篇)

    链接:http://www.cnblogs.com/vamei/archive/2013/03/31/2991531.html java快速教程第1课 从HelloWorld到面向对象 学习网址:ht ...

  8. Java ResultSet如何检查是否有任何结果

    本文翻译自:Java ResultSet how to check if there are any results Resultset has no method for hasNext. 结果集没 ...

  9. Java基础教程:反射基础

    Java基础教程:反射基础 引入反射 反射是什么 能够动态分析类能力的程序称为反射. 反射是一种很强大且复杂的机制. Class类 在程序运行期间,Java运行时系统始终为所有对象维护一个被称为运行时 ...

最新文章

  1. 设计一个扩展自抽象类geometricobject的新的triangle类_C++ 接口(抽象类)
  2. Jmeter入门实战(二)如何使用Jmeter的BeanShell断言,把响应数据中的JSON跟数据库中的记录对比...
  3. 全面解析Java中的String数据类型
  4. DataTable操作相关实例
  5. 如何做好软件测试管理工作,如何才能做好软件测试工作
  6. 5年赚50倍的段永平:这几家公司正在长长的坡上滚着厚厚的雪
  7. Ubuntu环境下NFS服务器搭建
  8. php微信卡包sdk,微信卡包会员系统
  9. 约束的操作 - 增加 删除 禁止 启用
  10. QQ心跳包格式分析 监听局域网QQ号代码
  11. 杂项工具WinHex
  12. 使用Sinc卷积从原始音频数据进行轻量级的端到端语音识别
  13. 欧姆龙PLC分频电路
  14. 运行时错误91问题汇总
  15. 32位系统的虚拟内存空间最大容量
  16. 服务器被ddos攻击的处置策略
  17. 电脑运行慢?更频繁地使用它
  18. Windows11快速入门
  19. 如何看待马云又唱歌又拍电影
  20. 解决Hexo博客引用网络图片无法显示的问题

热门文章

  1. 整合TextBox与Label 创建新控件--EFLabelText
  2. [转载] Python_range()_逆序
  3. [转载] Python 递归函数
  4. [转载] python3安装superset踩坑解决过程
  5. [转载] Python-科赫雪花(科克曲线)
  6. 初涉springboot(一)
  7. Java之戳中痛点 - (5)switch语句break不能忘以及default不同位置的用法
  8. Spring(三)Bean继续入门
  9. MFC使用简单总结(便于以后查阅)
  10. ExtAspNet应用技巧(十) - Grid导出为Excel文件(续)