← Back to Chapters

JDBC SELECT Operation

? JDBC SELECT Operation

? Quick Overview

The JDBC SELECT operation is used to retrieve data from a database table. It allows Java applications to read records using SQL queries and process them using ResultSet.

? Key Concepts

  • DriverManager establishes the database connection
  • Statement or PreparedStatement executes SQL queries
  • ResultSet holds retrieved records
  • Cursor moves row-by-row through ResultSet

? Syntax / Theory

A SELECT query fetches data without modifying the database. JDBC executes this query using executeQuery(), which always returns a ResultSet object.

? View Code Example
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create database connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/company","root","password");

// Create statement object
Statement stmt = con.createStatement();

// Execute SELECT query
ResultSet rs = stmt.executeQuery("SELECT id,name,salary FROM employee");

// Process result set
while(rs.next()){
System.out.println(rs.getInt("id")+" "+
rs.getString("name")+" "+
rs.getDouble("salary"));
}

// Close connection
con.close();

? Interactive Simulator: How rs.next() Works

Click the button to simulate the ResultSet Cursor moving through the database.

?️ Database Table (ResultSet)

  ID Name Salary
  1 Rahul 45000
  2 Anita 52000
  3 Mohan 48000

? Java Console Output

// Console waiting for execution...

? Live Output / Explanation

Sample Output

1 Rahul 45000
2 Anita 52000
3 Mohan 48000

Each row from the database is fetched sequentially using rs.next(). Column values are accessed using column names or index numbers.

✅ Tips & Best Practices

  • Always close Connection, Statement, and ResultSet
  • Use PreparedStatement for dynamic queries
  • Avoid using * in SELECT for better performance
  • Handle SQL exceptions properly

? Try It Yourself

  • Fetch only employees with salary above 50000
  • Display results in tabular format
  • Use PreparedStatement with WHERE clause