SELECT Queries

Reading data back from a database is one of the most common things you'll do in JDBC. The pattern is always the same: create a statement, run a query with it, and loop over the ResultSet it returns.

1. Create a Statement

A plain Statement is created directly from the Connection:

Statement stmt = conn.createStatement();

2. Run the Query With executeQuery

Calling .executeQuery(sql) with a SELECT statement sends it to the database and returns a ResultSet — an object representing the rows that came back. It doesn't hold all the data in memory at once; it acts more like a cursor pointing into the results.

ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM users");

3. Iterate With rs.next()

A fresh ResultSet starts positioned before the first row. Calling rs.next() advances it to the next row and returns true if there is one, or false once you've run out of rows — which makes it the natural condition for a while loop.

while (rs.next()) {
  // one iteration per row
}

4. Reading Columns: By Name or By Index

Inside the loop, you read each column with a typed getter. You can reference a column either by its name or by its position in the query — both work, but they behave a little differently.

StyleExampleNotes
By namers.getString("name")Clearer and safer if column order in the query ever changes
By indexrs.getString(1)Faster, but indexes are 1-based, not 0-based — a classic JDBC gotcha
Watch out: rs.getString(1) means "the first column", not the second. Coming from arrays or lists where indexing starts at 0, this trips up almost everyone the first time.

5. Always Close What You Open

ResultSet, Statement, and Connection should all be closed when you're done — closing a Statement also closes any ResultSet it produced, but it's still good practice to close explicitly, or better yet, let try-with-resources handle all three for you.

Full Worked Example

Example: Querying a users Table

import java.sql.*;

public class SelectUsersExample {
  public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306/coding_with_sonu";

    try (Connection conn = DriverManager.getConnection(url, "root", "");
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM users")) {

      while (rs.next()) {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        int age = rs.getInt("age");

        System.out.println(id + " - " + name + " - " + age);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    // conn, stmt, and rs are all closed automatically here
  }
}
Reminder: this is a static, correct code sample meant to be copied into your own Java project — this website only runs PHP, so nothing above executes live on this page.
Next up: Head to INSERT, UPDATE & DELETE to see how to modify data instead of just reading it.