Java ResultSet getString()

In this guide, you will learn about the ResultSet getString() method in Java programming and how to use it with an example.

1. ResultSet getString() Method Overview

Definition:

The getString() method of the java.sql.ResultSet interface retrieves the value of the specified column as a String in the current row of a ResultSet object. It is widely used for reading SQL CHAR, VARCHAR, and other string-type fields.

Syntax:

1. String getString(int columnIndex) throws SQLException
2. String getString(String columnLabel) throws SQLException

Parameters:

- columnIndex (int): the first column is 1, the second is 2, etc.

- columnLabel (String): the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column.

Key Points:

- A ResultSet object maintains a cursor pointing to its current row of data. The getString() method retrieves the value at the specified column in the current row.

- The getString() method can be used to retrieve values from columns that have string-compatible types such as CHAR, VARCHAR, LONGVARCHAR, NUMERIC, DECIMAL, BIT, BOOLEAN, TINYINT, SMALLINT, INTEGER, BIGINT, REAL, FLOAT, DOUBLE, BINARY, VARBINARY, LONGVARBINARY, DATE, TIME, and TIMESTAMP.

- If the column value is SQL NULL, the getString() method returns null.

- It is recommended to use ResultSet.wasNull() to check whether the last value read was SQL NULL.

- A SQLException will be thrown if the columnIndex is not valid or if a database access error occurs.

2. ResultSet getString() Method Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ResultSetGetStringExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/testdb";
        String jdbcUsername = "root";
        String jdbcPassword = "password";

        String query = "SELECT id, name FROM users";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

ID: 1, Name: John Doe
ID: 2, Name: Jane Doe
... (other rows from the 'users' table)

Explanation:

In this example, we established a JDBC connection to a MySQL database and executed a SQL query to retrieve id and name columns from the users table. We used the getString() method of the ResultSet interface to retrieve the name of each user in the table. For each row in the result set, we printed the id and name to the console.

Comments