Friday, 25 July 2014

JDBC Read Records Demo

Enjoying Java & Database Tutorials?

Subscribe to Ram N Java on YouTube for beginner-friendly coding lessons and hands-on demos!

🔔 Subscribe to Channel

How to Read and Retrieve Records Using JDBC in Java

Reading data from a database is one of the most frequently executed operations in enterprise applications. In SQL, you query stored information using the SELECT statement. In Java, JDBC (Java Database Connectivity) provides the Statement and ResultSet interfaces to execute these queries and process table records seamlessly.

The SQL SELECT Statement

To retrieve stored rows from a database table, use the standard SELECT command:

SELECT id, first_name, last_name, email FROM students;

This query returns a tabular dataset containing every matching record from the students table.

Step-by-Step Java Implementation

Follow these standard steps to fetch and display database records in Java:

  1. Establish Connection: Connect to your target database using DriverManager.getConnection().
  2. Create a Statement: Obtain a Statement object by calling connection.createStatement().
  3. Execute the Query: Call executeQuery() with your SQL statement, which returns a populated ResultSet.
  4. Iterate and Extract: Use a while (resultSet.next()) loop alongside getter methods such as getInt() and getString() to extract column values.
  5. Clean Up Resources: Close the ResultSet, Statement, and Connection using try-with-resources.

Watch More JDBC Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=JhD69W0xTMA

Click the below Image to Enlarge

JDBCSelectRecordsDemo Project Dir Structure
JDBC Read Records Demo
JDBC Read Records Demo

JDBCSelectRecords.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCSelectRecords
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

    public static void main(String[] args)
    {

        JDBCSelectRecords jdbcSelectRecords = new JDBCSelectRecords();
        jdbcSelectRecords.getCityInformation();

    }

    private void getCityInformation()
    {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try
        {
            /*
             * Register the JDBC driver in DriverManager
             */

            Class.forName(JDBC_DRIVER);

            /*
             * Establish connection to the Database using DriverManager
             */

            connection = DriverManager
                    .getConnection(DB_URL, USERNAME, PASSWORD);

            String sql = "select * from city";

            /*
             * Execute the query
             */
            preparedStatement = connection.prepareStatement(sql);

            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next())
            {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String countryCode = rs.getString(3);
                String district = rs.getString(4);
                int population = rs.getInt(5);

                /*
                 * Display values
                 */
                System.out.print("ID: " + id);
                System.out.print(", Name: " + name);
                System.out.print(", CountryCode: " + countryCode);
                System.out.print(", District: " + district);
                System.out.println(", Population: " + population);
            }

            rs.close();

        }
        catch (SQLException se)
        {
            /*
             * Handle errors for JDBC
             */
            se.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            /*
             * Handle errors for Class.forName
             */
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if (preparedStatement != null)
                {
                    preparedStatement.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
            try
            {
                if (connection != null)
                {
                    connection.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
        }

    }
}

Output
ID: 1, Name: Kabul, CountryCode: AFG, District: Kabol, Population: 1780000
ID: 2, Name: Qandahar, CountryCode: AFG, District: Qandahar, Population: 237500
ID: 3, Name: Herat, CountryCode: AFG, District: Herat, Population: 186800
ID: 4, Name: Mazar-e-Sharif, CountryCode: AFG, District: Balkh, Population: 127800
ID: 5, Name: Amsterdam, CountryCode: NLD, District: Noord-Holland, Population: 4000
ID: 6, Name: Rotterdam, CountryCode: NLD, District: Zuid-Holland, Population: 4000
ID: 7, Name: Haag, CountryCode: NLD, District: Zuid-Holland, Population: 440900
ID: 8, Name: Utrecht, CountryCode: NLD, District: Utrecht, Population: 234323
ID: 9, Name: Eindhoven, CountryCode: NLD, District: Noord-Brabant, Population: 201843
ID: 10, Name: Tilburg, CountryCode: NLD, District: Noord-Brabant, Population: 193238
ID: 11, Name: Groningen, CountryCode: NLD, District: Groningen, Population: 172701
ID: 12, Name: Breda, CountryCode: NLD, District: Noord-Brabant, Population: 160398
ID: 13, Name: Apeldoorn, CountryCode: NLD, District: Gelderland, Population: 153491
ID: 14, Name: Nijmegen, CountryCode: NLD, District: Gelderland, Population: 152463
ID: 15, Name: Enschede, CountryCode: NLD, District: Overijssel, Population: 149544
ID: 16, Name: Haarlem, CountryCode: NLD, District: Noord-Holland, Population: 148772
ID: 17, Name: Almere, CountryCode: NLD, District: Flevoland, Population: 142465
ID: 18, Name: Arnhem, CountryCode: NLD, District: Gelderland, Population: 138020
ID: 19, Name: Zaanstad, CountryCode: NLD, District: Noord-Holland, Population: 135621
ID: 20, Name: ´s-Hertogenbosch, CountryCode: NLD, District: Noord-Brabant, Population: 129170
ID: 21, Name: Amersfoort, CountryCode: NLD, District: Utrecht, Population: 126270
ID: 22, Name: Maastricht, CountryCode: NLD, District: Limburg, Population: 122087
ID: 23, Name: Dordrecht, CountryCode: NLD, District: Zuid-Holland, Population: 119811
ID: 24, Name: Leiden, CountryCode: NLD, District: Zuid-Holland, Population: 117196
ID: 25, Name: Haarlemmermeer, CountryCode: NLD, District: Noord-Holland, Population: 110722

-----
-----
-----
Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCSelectRecordsDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCSelectRecordsDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials