To select record from table using jdbc select statement you can execute select query against the database which will fetch all record in ResultSet object and once you get ResultSet object you could iterate it to get all records as example shown below:

Note: Here we are using MySQL database.

package com.javahonk;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatement {

    public static void main(String[] args) {

	Connection connection = null;
	Statement statement = null;
	ResultSet resultSet = null;

	try {
	    // Register JDBC Driver
	    Class.forName("com.mysql.jdbc.Driver");
	    // Open connection
	    connection = DriverManager.getConnection(
		    "jdbc:mysql://localhost:3306/javahonk", "root",
		    "admin");
	    // Create query set value and execute statement

	    String sql = "SELECT * FROM employee";
	    statement=connection.createStatement();	    
	    resultSet = statement.executeQuery(sql);

	    while (resultSet.next()) {
		String firstName = resultSet.getString("First_Name");
		String LastName = resultSet.getString("Last_Name");

		System.out.println("First Name : " + firstName);
		System.out.println("Last Name : " + LastName);

	    }	   

	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    try {
		if (connection != null) {
		    connection.close();
		}
		if (resultSet != null) {
		    resultSet.close();
		}
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	}

    }

}

 

Output:

jdbc select statement

That’t all for jdbc select statement

Leave a Reply

Your email address will not be published. Required fields are marked *