Friday, 18 July 2014

JDBC ResultSet 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 Use JDBC ResultSet in Java

When you query a database using SQL SELECT statements, the returned rows must be stored and processed by your application. In Java, JDBC (Java Database Connectivity) represents this tabular dataset using the ResultSet interface. A ResultSet acts as a cursor pointing to one row of data at a time, making it easy to iterate and retrieve column values.

How the ResultSet Cursor Works

Initially, the ResultSet cursor is positioned before the very first row. Calling the next() method moves the cursor forward to the next row. It returns true as long as more rows are available, and false when the end of the dataset is reached.

while (resultSet.next()) {
  int id = resultSet.getInt("id");
  String name = resultSet.getString("name");
}

Step-by-Step Java Implementation

Follow these standard steps to retrieve and traverse data with a ResultSet in JDBC:

  1. Establish Database Connection: Create a connection using DriverManager.getConnection().
  2. Create Statement: Obtain a Statement or PreparedStatement instance.
  3. Execute Query: Call executeQuery("SELECT ...") to receive your ResultSet object.
  4. Extract Field Data: Read values using getter methods such as getInt(), getString(), or getDouble() by column label or 1-based index.
  5. Clean Up Resources: Ensure ResultSet, Statement, and Connection are cleanly closed using try-with-resources.

Watch More JDBC Tutorials


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

Click the below Image to Enlarge

JDBCResultSetDemo Project Dir Structure

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

public class JDBCResultSetDemo
{
    // 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 )
    {

        JDBCResultSetDemo jdbcResultSetDemo = new JDBCResultSetDemo();
        jdbcResultSetDemo.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 limit ?";

            /*
             * Execute the query
             */
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 10);

            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);
                
                
                name = rs.getString("CountryCode");             
                System.out.println(", Getby Column Name CountryCode: " + name);
                
            }

            rs.close();

        }
        catch( SQLException se )
        {
            /*
             * Handle errors for JDBC
             */
            se.printStackTrace();
        }
        catch( ClassNotFoundException e )
        {
            /*
             * Handle errors for Class.forName
             */
            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
, Getby Column Name CountryCode: AFG
ID: 2, Name: Qandahar, CountryCode: AFG, District: Qandahar, Population: 237500
, Getby Column Name CountryCode: AFG
ID: 3, Name: Herat, CountryCode: AFG, District: Herat, Population: 186800
, Getby Column Name CountryCode: AFG
ID: 4, Name: Mazar-e-Sharif, CountryCode: AFG, District: Balkh, Population: 127800
, Getby Column Name CountryCode: AFG
ID: 5, Name: Amsterdam, CountryCode: NLD, District: Noord-Holland, Population: 731200
, Getby Column Name CountryCode: NLD
ID: 6, Name: Rotterdam, CountryCode: NLD, District: Zuid-Holland, Population: 593321
, Getby Column Name CountryCode: NLD
ID: 7, Name: Haag, CountryCode: NLD, District: Zuid-Holland, Population: 440900
, Getby Column Name CountryCode: NLD
ID: 8, Name: Utrecht, CountryCode: NLD, District: Utrecht, Population: 234323
, Getby Column Name CountryCode: NLD
ID: 9, Name: Eindhoven, CountryCode: NLD, District: Noord-Brabant, Population: 201843
, Getby Column Name CountryCode: NLD
ID: 10, Name: Tilburg, CountryCode: NLD, District: Noord-Brabant, Population: 193238
, Getby Column Name CountryCode: NLD

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCResultSetDemoApp Project Click the below link

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

See also:

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

    Post a Comment

    Tutorials