In this tutorial, we are going to understand the basic JDBC select program example. As we already discussed in the previous tutorials steps to create jdbc example, to do the select operation in JDBC we need to use the executeQuery() method.
While Executing the executeQuery() method, we need to keep in mind some important facts.
JDBC Select on executeQuery() :
- We can call the executeQuery() method on statement object to select the data from the database.
- executeQuery() method returns ResultSet object.
- The ResultSet object contains rows of table.
- The ResultSet object maintains the cursor, and it is initially positioned at before of the first row.
- To read the data of row by row, we need to move the curson to the next row by calling next() method available in ResultSet.
- The next() method returns a boolean value, either true or false.
- When there is a row available in ResultSet object then next() returns true if no more rows then it returns false.
- By default ResultSet object is non-scrollable. That means, a cursor of the ResultSet object can be moved in forward direction only.
- If require, we can convert a ResultSet object into Scrollable type. If the ResultSet object is scrollable then the cursor will be moved in forward and backward direction.
- One statement object can create only one ResultSet object at a time. If another ResultSet object is created by same statement object, then it automatically closes the previous ResultSet object.
ResultSet rs1 = stmt.executeQuery("select * from emp);
ResultSet rs2 = stmt.executeQuery("select * from dept);
Here rs1 is closed automatically, when rs2 is created.
JDBC Select Program Example :
Jdbc_Select_Example.java
package com.onlinetutorialspoint.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdbc_Select_Example {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getString(3));
}
rs.close();
stmt.close();
con.close();
}
}
Output :
101 Chandra hyd 102 Shekhar hyd
Happy Learning 🙂