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.
ResultSet rs1 = stmt.executeQuery("select * from emp);
ResultSet rs2 = stmt.executeQuery("select * from dept);
Here rs1 is closed automatically, when rs2 is created.
package com.navabitsolutions.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcSelectExample {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/navabitsolutions", "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();
}
}