Java ResultSet getInt()

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

1. ResultSet getInt() Method Overview

Definition:

The getInt() method of the java.sql.ResultSet interface retrieves the value of the specified column as an int in the current row of a ResultSet object. It is commonly used for reading SQL INTEGER type fields.

Syntax:

1. int getInt(int columnIndex) throws SQLException

2. int getInt(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 getInt() method retrieves the value at the specified column in the current row.

- The getInt() method can be used to retrieve values from columns that are integer-compatible types such as TINYINT, SMALLINT, and INTEGER.

- If the column value is SQL NULL, the getInt() method returns 0.

- 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 getInt() Method Example

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

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

        String query = "SELECT id, age 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");
                int age = resultSet.getInt("age");
                System.out.println("ID: " + id + ", Age: " + age);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

ID: 1, Age: 30
ID: 2, Age: 25
... (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 age columns from the users table. We used the getInt() method of the ResultSet interface to retrieve the age of each user in the table. For each row in the result set, we printed the id and age to the console.

Comments