JDBC Statement Select Query Example

JDBC Statement Select Query Example

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