Sunday, 3 August 2014

JDBC Updatable ResultSet Demo

Enjoyed this tutorial?

Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!

▶ Subscribe Now

What is an Updatable ResultSet in JDBC?

By default, a JDBC ResultSet is read-only and forwards-only. However, JDBC allows you to configure a ResultSet with concurrency support so that you can modify, update, and insert new records directly through the ResultSet object itself without executing separate SQL UPDATE or INSERT statements.

Configuring Statement for Updatability

To enable updates on your query results, supply the concurrency type ResultSet.CONCUR_UPDATABLE when preparing or creating the statement:

PreparedStatement ps = connection.prepareStatement(
    "SELECT id, name, countrycode, district, population FROM city LIMIT ?",
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE
);

How to Update Existing Rows

To update an existing row, position the cursor onto that row, call the appropriate updateXxx() method, and commit the changes using updateRow():

// Move cursor to the 5th row
rs.absolute(5);

// Update column value in cursor buffer
rs.updateInt("population", 50000);

// Commit update directly into the database
rs.updateRow();

How to Insert New Rows

You can also create brand-new records using the dedicated staging row via moveToInsertRow():

// Move cursor to the staging insert row
rs.moveToInsertRow();

// Provide values for columns
rs.updateInt(1, 4080);
rs.updateString(2, "Chennai");
rs.updateString(3, "IND");
rs.updateString(4, "Tamil Nadu");
rs.updateInt(5, 200000);

// Insert row into database table
rs.insertRow();

Recommended Related Tutorials

Explore more hands-on tutorials on JDBC ResultSets and navigation:


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

Click the below Image to Enlarge

JDBCUpdatableResultSetDemo Project Dir Structure
JDBC Updatable ResultSet Demo
JDBC Updatable ResultSet Demo
JDBCUpdatableResultSetDemo.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

        JDBCUpdatableResultSetDemo jdbcUpdatableResultSetDemo = 
                                                 new JDBCUpdatableResultSetDemo();
        jdbcUpdatableResultSetDemo.updateOrInsertCityInformation();

    }

    private void updateOrInsertCityInformation()
    {
        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,
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            preparedStatement.setInt(1, 10);

            ResultSet rs = preparedStatement.executeQuery();

            /*
             * Moves the cursor to the fifth row of rs and update the column
             * information
             */

            rs.absolute(5);
            rs.updateInt("Population", 50000);
            rs.updateRow();
            System.out.println("5th row population column is updated");

            /*
             * Moves cursor to the insert row
             */

            rs.moveToInsertRow();
            rs.updateInt(1, 4080);
            rs.updateString(2, "Chennai");
            rs.updateString(3, "IND");
            rs.updateString(4, "TamilNadu");
            rs.updateInt(5, 200000);
            rs.insertRow();

            System.out.println("4080th row has been inserted in city table");

            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
5th row population column is updated
4080th row has been inserted in city table

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCUpdatableResultSetDemoApp Project Click the below link

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

See also:

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

    Post a Comment

    Tutorials