java string contains,Java ResultSet教程

 2023-11-19 阅读 32 评论 0

摘要: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

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 Class Hierarchy
Java ResultSet類層次結構

java string contains、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.

jdbc resultset, 我們將使用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

java field.set,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)

java queue poll。 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))

Java編程。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.

java resultset。 在這種情況下,我們可以對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 long

    long getLong( int columnIndex) 拋出 SQLException:該方法返回指定columnIndex的值, 只要long
  • String getString(int columnIndex) throws SQLException: This method returns value of specified columnIndex as String

    String getString( int columnIndex) 引發 SQLException:此方法將指定的columnIndex的值作為String返回
  • java.sql.Date getDate(int columnIndex) throws SQLException: This method returns value of specified columnIndex as java.sql.Date

    java.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的值。

java contains、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基礎開發教程、 參考 : Java文檔

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/183202.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息