Easy learning with example program codes

JDBC Statement select records example

The JDBC statement is used to execute queries against the database. Let us study JDBC Statement by select records example.


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.codesjava.util.JDBCUtil;
 * This class is used to select a list of records from DB table.
 * @author codesjava
public class JDBCTest {
	public static void main(String args[]){
		Connection conn = null;
		Statement statement = null;
		String query = "select EMPLOYEE_ID, NAME from EMPLOYEE";
			//get connection
			conn = JDBCUtil.getConnection();
			//create statement
			statement = conn.createStatement();
			//execute query
			ResultSet rs = statement.executeQuery(query);
			while ( {				 
			   String empId = rs.getString("EMPLOYEE_ID");
			   String empName = rs.getString("NAME");
			   System.out.println("EmpId : " + empId);
			   System.out.println("EmpName : " + empName); 
			//close connection
		}catch(Exception e){

import java.sql.Connection;
import java.sql.DriverManager;
 * This is a utility class for JDBC connection.
 * @author codesjava
public class JDBCUtil {
	//JDBC and database properties.
	private static final String DB_DRIVER = 
	private static final String DB_URL = 
	private static final String DB_USERNAME = "system";
	private static final String DB_PASSWORD = "oracle";
	public static Connection getConnection(){
		Connection conn = null;
			//Register the JDBC driver
			//Open the connection
			conn = DriverManager.
			if(conn != null){
			   System.out.println("Successfully connected.");
			   System.out.println("Failed to connect.");
		}catch(Exception e){
		return conn;


Successfully connected.
EmpId : 7
EmpName : Harish Yadav
EmpId : 2
EmpName : vivek
EmpId : 3
EmpName : Himanshu
EmpId : 1
EmpName : Bharat
EmpId : 4
EmpName : Bharti
EmpId : 8
EmpName : Abhishek Rathor
EmpId : 11
EmpName : Harish Kansal
EmpId : 12
EmpName : Vivek Solenki

Download this example.
Next Topic: JDBC Statement deletes a record example.
Previous Topic: JDBC Statement updates a record example.

Related Topics:

JDBC Statement creates a table example.
JDBC Statement inserts a record example.
JDBC Statement updates a record example.
JDBC Statement select records example.
JDBC Statement deletes a record example.
JDBC Statement batch update example.


Posted in JDBC   

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki