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.
A SELECT query fetches data without modifying the database. JDBC executes this query using executeQuery(), which always returns a ResultSet object.
// 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();
Click the button to simulate the ResultSet Cursor moving through the database.
| ID | Name | Salary | |
|---|---|---|---|
| 1 | Rahul | 45000 | |
| 2 | Anita | 52000 | |
| 3 | Mohan | 48000 |
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.