JDBC Statement Select Query Example

JDBC Statement Select Query Example

By Yashwant Chavan, Views 878, Date 26-May-2012

JDBC Statement Select Query Example

tags java

Jdbc Statement Select query example

package com.technicalkeeda.jdbc;

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

public class JdbcSelectExample {

    public static void main(String[] args) {

        JdbcSelectExample example = new JdbcSelectExample();
        example.select();
    }

    public void select() {
        Connection connection = null;
        Statement statement = null;

        try {
            String sql = "SELECT * from trn_employee";
            connection = getConnection();
            statement = connection.createStatement();

            ResultSet rs = statement.executeQuery(sql);

            while (rs.next()) {

                String empId = rs.getString("emp_id");
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                String dept = rs.getString("dept");

                System.out.println("Emp Id:- " + empId + " First Name:- " + firstName + " Last Name:- " + lastName +
                    " Dept:- " + dept);

            }

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        } finally {

            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }

        }
    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/technicalkeeda", "root", "");

        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return connection;
    }
}

Output

Emp Id:- 1 First Name:- Yashwant Last Name:- Chavan Dept:- IT
Emp Id:- 2 First Name:- Vinay Last Name:- Patil Dept:- SALES
Emp Id:- 3 First Name:- Jatin Last Name:- More Dept:- HR
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]