Saturday, 30 August 2014

JDBC : JDBCRowSet Event Handling

Learn Java & JDBC The Easy Way!

Subscribe to Ram N Java for hands-on tutorials, code examples, and clear programming explanations.

SUBSCRIBE NOW

What Is Event Handling in JDBCRowSet?

In standard JDBC, result sets passively deliver data. However, the RowSet interface takes connectivity a step further by supporting the JavaBeans event model.

With JDBCRowSet Event Handling, your application can be notified immediately whenever key actions take place on the dataset—such as navigating across rows, modifying record values, or refreshing query results.

The Key Components: RowSetListener & RowSetEvent

Event handling in JDBCRowSet revolves around two core Java interfaces from the javax.sql package:

  • RowSetListener: An interface implemented by any class that wants to listen to and handle RowSet notifications.
  • RowSetEvent: An event object generated by the RowSet whenever an action occurs, which gets passed directly to the listener methods.

The Three Primary RowSet Events

The RowSetListener interface defines three distinct methods to respond to different types of database actions:

  1. cursorMoved(RowSetEvent event): Triggered whenever the cursor moves from one row to another (for example, when calling next(), previous(), first(), or last()).
  2. rowChanged(RowSetEvent event): Triggered whenever a specific row is modified, such as inserting a new row, updating existing values, or deleting a record.
  3. rowSetChanged(RowSetEvent event): Triggered whenever the entire content of the RowSet changes, such as executing a fresh query via execute().

How to Register a Listener

Connecting your listener to your JDBCRowSet instance is simple and follows the standard Java listener pattern:

jdbcRowSet.addRowSetListener(new MyRowSetListener());

Once registered, the component will automatically receive updates, allowing you to log changes, update UI elements, or trigger custom business logic in real time!

Recommended JDBCRowSet Tutorials

Check out these related tutorials to dive deeper into JDBCRowSet:


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

Click the below Image to Enlarge
JDBCRowSet Event Handling
JDBCRowSet Event Handling
JDBCRowSet Event Handling
See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC : JDBCRowSet Demo

    Enjoying this Java Tutorial?

    Subscribe to Ram N Java for regular, beginner-friendly programming tutorials and real-world coding demos!

    SUBSCRIBE NOW

    What is a JDBCRowSet?

    In standard Java Database Connectivity (JDBC), working with standard ResultSet objects often requires manually opening connections, managing statements, and tracking resource life cycles. A JDBCRowSet wraps a standard ResultSet into a JavaBean component, making database handling flexible, easy to configure, and scrollable by default.

    Key Steps to Create and Use JDBCRowSet

    To implement a JdbcRowSet in your Java application, you follow these straightforward steps:

    • Obtain the RowSetProvider: Call RowSetProvider.newFactory() to obtain an instance of RowSetFactory.
    • Create JdbcRowSet: Use rowSetFactory.createJdbcRowSet() to get your row set instance.
    • Configure Connection Parameters: Set the database connection URL, username, and password using dedicated setter methods.
    • Define Query & Parameters: Set the SQL statement via setCommand() and bind query placeholders with setters like setString().
    • Execute and Process: Trigger execute() to load the records, iterate through the row set, and access column values smoothly.

    Complete Java Code Example

    import java.sql.SQLException;
    import java.util.Scanner;
    import javax.sql.rowset.JdbcRowSet;
    import javax.sql.rowset.RowSetFactory;
    import javax.sql.rowset.RowSetProvider;
    
    public class JdbcRowSetDemo {
    
        public static void main(String[] args) {
            JdbcRowSetDemo demo = new JdbcRowSetDemo();
            try (Scanner scanner = new Scanner(System.in)) {
                System.out.print("Enter Country Code (e.g., IND, USA): ");
                String countryCode = scanner.next();
                demo.getCityInformation(countryCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public void getCityInformation(String countryCode) {
            try {
                // 1. Create RowSetFactory
                RowSetFactory factory = RowSetProvider.newFactory();
    
                // 2. Create JdbcRowSet instance
                try (JdbcRowSet jdbcRowSet = factory.createJdbcRowSet()) {
    
                    // 3. Set connection properties
                    jdbcRowSet.setUrl("jdbc:mysql://localhost:3306/world");
                    jdbcRowSet.setUsername("root");
                    jdbcRowSet.setPassword("password");
    
                    // 4. Set SQL query command and bind parameters
                    jdbcRowSet.setCommand("SELECT ID, Name, CountryCode, District, Population FROM city WHERE CountryCode = ?");
                    jdbcRowSet.setString(1, countryCode);
    
                    // 5. Execute query
                    jdbcRowSet.execute();
    
                    // 6. Iterate through the records
                    while (jdbcRowSet.next()) {
                        System.out.println("ID: " + jdbcRowSet.getInt("ID"));
                        System.out.println("Name: " + jdbcRowSet.getString("Name"));
                        System.out.println("CountryCode: " + jdbcRowSet.getString("CountryCode"));
                        System.out.println("District: " + jdbcRowSet.getString("District"));
                        System.out.println("Population: " + jdbcRowSet.getInt("Population"));
                        System.out.println("------------------------------------------");
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    Watch More Related JDBC Tutorials


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

    Click the below Image to Enlarge
    JDBCRowSet 
    JDBCRowSet 
    JDBCRowSet 

    JDBCRowSetDemo.java
    import java.sql.SQLException;
    import java.util.Scanner;
    
    import javax.sql.rowset.JdbcRowSet;
    import javax.sql.rowset.RowSetFactory;
    import javax.sql.rowset.RowSetProvider;
    
    public class JDBCRowSetDemo
    {
        // 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 )
        {
            JDBCRowSetDemo jdbcRowSetDemo = new JDBCRowSetDemo();
            Scanner scanner = new Scanner(System.in);
            while( true )
            {
                System.out.print("Enter City Country Code :");
                String cityCountrycode = scanner.nextLine();
    
                if( cityCountrycode.equals("exit") )
                {
                    break;
                }
    
                jdbcRowSetDemo.getCityInformation(cityCountrycode);
    
            }
            scanner.close();
        }
    
        private void getCityInformation( String cityCountrycode )
        {
            JdbcRowSet jdbcRowSet = null;
            try
            {
                /*
                 * Using RowSetFactory create the JdbcRowSet object.
                 */
                RowSetFactory rowSetFactory = RowSetProvider.newFactory();
                jdbcRowSet = rowSetFactory.createJdbcRowSet();
    
                /*
                 * Set the JdbcRowSet properties [URL,username,password,command]
                 */
                jdbcRowSet.setUrl(DB_URL);
                jdbcRowSet.setUsername(USERNAME);
                jdbcRowSet.setPassword(PASSWORD);
    
                /*
                 * Sets the command property with a query that produces a ResultSet
                 * object containing all the data in the table
                 */
    
                jdbcRowSet.setCommand("select * from city where countrycode=?");
                jdbcRowSet.setString(1, cityCountrycode);
    
                /*
                 * The execute method does many things for you in the background:
                 * 
                 *  1.It makes a connection to the database using the values you assigned to the url,
                 *    username, and password properties.
                 *    
                 *  2.It executes the query you set in the command property.
                 *  
                 *  3.It reads the data from the resulting ResultSet object into the jdbcRs object.
                 *  
                 */         
                jdbcRowSet.execute();
    
                /*
                 *  Iterate the jdbcRowSet and get each row information
                 *  of city table.
                 */
                
                while( jdbcRowSet.next() )
                {
                    int id = jdbcRowSet.getInt(1);
                    String name = jdbcRowSet.getString(2);
                    String countryCode = jdbcRowSet.getString(3);
                    String district = jdbcRowSet.getString(4);
                    int population = jdbcRowSet.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);
                }
                
            }
            catch( SQLException se )
            {
                se.printStackTrace();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }   
            
            finally
            {
                if(jdbcRowSet!=null)
                {
                    try
                    {
                        jdbcRowSet.close();
                    }
                    catch( SQLException e )
                    {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    }
    
    
    Output
    Enter City Country Code :ind
    ID: 1024, Name: Mumbai (Bombay), CountryCode: IND, District: Maharashtra, Population: 10500000
    ID: 1025, Name: Delhi, CountryCode: IND, District: Delhi, Population: 7206704
    ID: 1026, Name: Calcutta [Kolkata], CountryCode: IND, District: West Bengali, Population: 4399819
    ID: 1027, Name: Chennai (Madras), CountryCode: IND, District: Tamil Nadu, Population: 3841396
    
    ---
    ---
    
    
    Enter City Country Code :pak
    ID: 2822, Name: Karachi, CountryCode: PAK, District: Sindh, Population: 9269265
    ID: 2823, Name: Lahore, CountryCode: PAK, District: Punjab, Population: 5063499
    ID: 2824, Name: Faisalabad, CountryCode: PAK, District: Punjab, Population: 1977246
    ID: 2825, Name: Rawalpindi, CountryCode: PAK, District: Punjab, Population: 1406214
    
    ---
    ---
    
    Enter City Country Code :exit
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download /JDBCRowSet_Read_DemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Wednesday, 27 August 2014

    JDBCRowSet

    Master Java & Database Concepts!

    Subscribe to Ram N Java for in-depth, beginner-friendly JDBC and Java tutorials.

    SUBSCRIBE NOW

    What Is JDBCRowSet?

    In traditional JDBC, working with a standard ResultSet requires you to manage explicit connections, create statements, and deal with forward-only iteration by default.

    JDBCRowSet is an enhanced, connected wrapper around a standard ResultSet. It implements the JavaBeans component model, which allows you to configure database connection properties using straightforward setter and getter methods, making your code significantly cleaner and more reusable.

    Why Use JDBCRowSet Over Standard ResultSet?

    JDBCRowSet brings several major advantages to modern Java applications:

    • Scrollable and Updatable by Default: Unlike a standard ResultSet which is forward-only and read-only by default, a JDBCRowSet is always scrollable (allowing forward and backward traversal) and updatable out of the box.
    • JavaBeans Architecture: It can be configured like a JavaBean with standard properties such as url, username, password, and command.
    • Built-in Event Handling: It supports event listener registration via RowSetListener, allowing your app to track cursor movements and data modifications in real time.

    How to Create and Configure a JDBCRowSet

    Starting with Java 7 and onwards, you instantiate a JdbcRowSet using the RowSetProvider factory:

    RowSetFactory factory = RowSetProvider.newFactory();
    JdbcRowSet rowSet = factory.createJdbcRowSet();
    
    rowSet.setUrl("jdbc:mysql://localhost:3306/your_db");
    rowSet.setUsername("root");
    rowSet.setPassword("password");
    rowSet.setCommand("SELECT id, name, salary FROM employee");
    rowSet.execute();

    Key Features Summary

    • Maintains an active connection to the database while in use.
    • Simplifies database navigation with methods like previous(), first(), last(), and absolute().
    • Ideal for client-side applications that need a lightweight, JavaBean-compliant data view.

    Recommended JDBC Tutorials

    Continue exploring JDBC concepts with these recommended videos from our channel:


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

    Click the below Image to Enlarge
    JDBCRowSet
    JDBCRowSet
    JDBCRowSet
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC Transaction Management Demo

    🚀 Master Java database programming, JDBC transactions, and MySQL!

    🔔 Subscribe to Ram N Java on YouTube

    What Is Transaction Management in JDBC?

    A transaction represents a single unit of work consisting of one or more SQL statements. By default, JDBC connections operate in auto-commit mode, which means every individual SQL statement is permanently committed to the database as soon as it completes execution.

    In real-world business scenarios, multiple SQL operations must succeed together as an atomic unit (Atomicity in ACID properties). If any single statement fails, all previously executed statements in that transaction must be rolled back so that the database remains in a consistent state.

    How to Control Transactions Programmatically

    JDBC provides three primary methods on the java.sql.Connection interface to manage transactions manually:

    • conn.setAutoCommit(false); — Disables automatic committing so you can group multiple operations into a single transaction boundary.
    • conn.commit(); — Permanently applies and persists all SQL statements executed within the transaction.
    • conn.rollback(); — Undoes all changes made within the current transaction if any error or exception occurs.

    Complete Java Source Code Example

    The following Java program connects to MySQL, turns off auto-commit, executes three INSERT statements, and rolls back the transaction if any statement fails:

    package com.ram.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBCTransactionManagementDemo {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/world";
        static final String USER = "root";
        static final String PASS = "root";
    
        public static void main(String[] args) {
            JDBCTransactionManagementDemo demo = new JDBCTransactionManagementDemo();
            demo.addCityInformation();
        }
    
        public void addCityInformation() {
            Connection conn = null;
            Statement stmt = null;
    
            try {
                // Step 1: Register JDBC driver and open connection
                Class.forName(JDBC_DRIVER);
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
    
                // Step 2: Disable auto-commit to take manual control of transactions
                conn.setAutoCommit(false);
    
                stmt = conn.createStatement();
    
                // SQL 1: Insert city record
                String sql1 = "INSERT INTO city (ID, Name, CountryCode, District, Population) "
                            + "VALUES (6000, 'CityA', 'USA', 'DistrictA', 100000)";
                stmt.executeUpdate(sql1);
                System.out.println("SQL 1 executed successfully.");
    
                // SQL 2: Insert city record
                String sql2 = "INSERT INTO city (ID, Name, CountryCode, District, Population) "
                            + "VALUES (6001, 'CityB', 'USA', 'DistrictB', 200000)";
                stmt.executeUpdate(sql2);
                System.out.println("SQL 2 executed successfully.");
    
                // SQL 3: Insert city record
                String sql3 = "INSERT INTO city (ID, Name, CountryCode, District, Population) "
                            + "VALUES (6002, 'CityC', 'USA', 'DistrictC', 300000)";
                stmt.executeUpdate(sql3);
                System.out.println("SQL 3 executed successfully.");
    
                // Step 3: Commit all statements if no exception occurred
                conn.commit();
                System.out.println("Transaction committed successfully!");
    
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
    
                // Step 4: Rollback entire transaction on error
                try {
                    if (conn != null) {
                        System.out.println("Exception encountered! Rolling back all transaction changes...");
                        conn.rollback();
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            } finally {
                // Step 5: Clean up resources
                try {
                    if (stmt != null) stmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    Key Steps & Best Practices

    • Turn Off Auto-Commit First: Always call conn.setAutoCommit(false) before executing any statement in the transaction.
    • Explicit Commit: Call conn.commit() only after all participating statements complete without throwing exceptions.
    • Rollback in Catch Block: Wrap your operations inside a try-catch block and invoke conn.rollback() inside catch to maintain database consistency.
    • Resource Cleanup: Always close statements and connections inside the finally block to prevent resource leaks.

    Related Tutorials You Might Enjoy


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

    Click the below Image to Enlarge

    JDBCTransactionManagementDemo Project Dir Structure
    JDBC Transaction Management Demo
    JDBC Transaction Management Demo

    JDBCTransactionManagementDemo.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBCTransactionManagementDemo
    {
        // 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 )
        {
            JDBCTransactionManagementDemo jdbcTransactionManagementDemo =
                                                 new JDBCTransactionManagementDemo();
            jdbcTransactionManagementDemo.addCityInformation();
        }
    
        private void addCityInformation()
        {
            Connection connection = null;
            Statement statement = 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);
    
                /*
                 * Set auto-commit to false
                 */
                connection.setAutoCommit(false);
    
                String sql1 = "insert into city values(6000,'Bangalore','IND','Karnataka',400000)";
                String sql2 = "insert into city values(6001,'Channai','IND','TamilNadu',200000)";
                String sql3 = "insert into city values(6002,'Thiruvanathapuram','IND','Kerala',800000)";
    
                /*
                 * Execute the query
                 */
                statement = connection.createStatement();
    
                /*
                 * Execute each sql one by one
                 */
                statement.executeUpdate(sql1);
                System.out.println(sql1 + " : Sql1 is Successfully executed");
                statement.executeUpdate(sql2);
                System.out.println(sql2 + ": Sql2 is Successfully executed");
                statement.executeUpdate(sql3);
                System.out.println(sql3 + ": Sql3 is Successfully executed");
    
                /*
                 * If there is no error
                 */
                connection.commit();
    
                System.out
                        .println("Changes are committed and applied to the Database");
    
            }
            catch( SQLException se )
            {
                /*
                 * Handle errors for JDBC
                 */
                try
                {
                    /*
                     * If there is any error.
                     */
                    connection.rollback();
                    System.out
                            .println("Changes are rollbacked and not applied to the Database");
                }
                catch( SQLException e )
                {
                    e.printStackTrace();
                }
                se.printStackTrace();
            }
            catch( ClassNotFoundException e )
            {
                /*
                 * Handle errors for Class.forName
                 */
                e.printStackTrace();
            }
            catch( Exception e )
            {
                try
                {
                    /*
                     * If there is any error.
                     */
                    connection.rollback();
                    System.out
                            .println("Changes are rollbacked and not applied to the Database");
                }
                catch( SQLException e1 )
                {
    
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
            finally
            {
                /*
                 * finally block used to close resources
                 */
                try
                {
                    if( statement != null )
                    {
                        statement.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
                try
                {
                    if( connection != null )
                    {
                        connection.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
            }
    
        }
    }
    
    
    Output
    insert into city values(6000,'Bangalore','IND','Karnataka',400000) : Sql1 is Successfully executed
    insert into city values(6001,'Channai','IND','TamilNadu',200000): Sql2 is Successfully executed
    insert into city values(6002,'Thiruvanathapuram','IND','Kerala',800000): Sql3 is Successfully executed
    Changes are committed and applied to the Database
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCTransactionManagementDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC Transaction Management

    Master Java & JDBC With Us!

    Subscribe to Ram N Java for practical code demos, database tutorials, and beginner-friendly guides.

    SUBSCRIBE TO CHANNEL

    What Is Transaction Management in JDBC?

    In database programming, a transaction represents a single unit of work. It can group multiple SQL statements together inside what is called a transaction boundary.

    The fundamental rule of transaction management is straightforward:

    • If all SQL statements execute successfully, the changes are saved to the database.
    • If any single statement fails or throws an exception, all changes are discarded, leaving the database completely clean and unaffected.

    Default Auto-Commit Mode vs. Manual Control

    By default, a JDBC Connection operates in Auto-Commit mode (true). In this mode, each SQL statement is committed automatically the moment it finishes executing.

    To group multiple operations into your own custom transaction, you must disable auto-commit:

    connection.setAutoCommit(false);

    Commit vs. Rollback: Key Methods

    The JDBC Connection interface provides two primary methods to manage outcomes:

    • connection.commit(): When all SQL statements inside your transaction boundary execute without error, call commit() to make all updates permanent in the database.
    • connection.rollback(): If an error occurs (such as query 3 failing while queries 1 and 2 succeeded), invoke rollback(). This cancels all pending operations and restores the database to its initial state.

    Understanding ACID Properties

    Transaction management is guided by the four pillars of database integrity:

    1. Atomicity: "All or nothing" — either every statement succeeds, or none of them do.
    2. Consistency: Ensures that the database transitions strictly from one valid, consistent state to another.
    3. Isolation: Each ongoing transaction executes independently without interference from other concurrent transactions.
    4. Durability: Once a transaction is committed, changes remain permanent, even during system crashes or power failures.

    Explore More JDBC Tutorials

    Deepen your understanding of Java database development with these tutorials:


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

    Click the below Image to Enlarge
    JDBC Transaction Management
    JDBC Transaction Management
    JDBC Transaction Management
    JDBC Transaction Management
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Saturday, 23 August 2014

    JDBC : Retrieve File

    🚀 Master Java database programming, JDBC BLOB/CLOB handling, and MySQL!

    🔔 Subscribe to Ram N Java on YouTube

    Reading Large Files and Documents from MySQL with JDBC

    Databases frequently store documents, configurations, text files, and binary assets inside character or binary columns such as TEXT, LONGTEXT, CLOB, or BLOB.

    In JDBC, you can retrieve these files by fetching them as a character stream using getCharacterStream() or as a reader from the ResultSet. By piping the stream through a FileWriter or FileOutputStream, your Java application can export and reconstruct the exact file onto your local filesystem.

    The MySQL Database Table Structure

    Consider a table designed to store file details along with text content or file data:

    CREATE TABLE `file_repository` (
        `id` INT NOT NULL AUTO_INCREMENT,
        `file_name` VARCHAR(255) NOT NULL,
        `file_data` LONGTEXT,
        PRIMARY KEY (`id`)
    );

    Complete Java Source Code Example

    The following Java application connects to MySQL, queries the record containing the stored file data, streams the content using a Reader, and writes it directly to a local target destination:

    package com.ram.jdbc;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Reader;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class RetrieveFileFromDBDemo {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/world";
        static final String USER = "root";
        static final String PASS = "root";
    
        public static void main(String[] args) {
            RetrieveFileFromDBDemo demo = new RetrieveFileFromDBDemo();
            // Retrieve file for record ID 1 and save to destination directory
            demo.retrieveFile(1, "output_retrieved.txt");
        }
    
        public void retrieveFile(int recordId, String outputFileName) {
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            FileWriter writer = null;
            Reader reader = null;
    
            try {
                // Step 1: Register driver and establish connection
                Class.forName(JDBC_DRIVER);
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
    
                // Step 2: Prepare query to fetch the file record
                String sql = "SELECT file_name, file_data FROM file_repository WHERE id = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, recordId);
    
                // Step 3: Execute query
                rs = pstmt.executeQuery();
    
                if (rs.next()) {
                    String originalFileName = rs.getString("file_name");
                    System.out.println("Found record for file: " + originalFileName);
    
                    // Step 4: Stream character data using Reader
                    reader = rs.getCharacterStream("file_data");
    
                    File outputFile = new File(outputFileName);
                    writer = new FileWriter(outputFile);
    
                    int character;
                    while ((character = reader.read()) != -1) {
                        writer.write(character);
                    }
    
                    System.out.println("File successfully downloaded and saved to: " + outputFile.getAbsolutePath());
                } else {
                    System.out.println("No file found with ID: " + recordId);
                }
    
            } catch (ClassNotFoundException | SQLException | IOException e) {
                e.printStackTrace();
            } finally {
                // Step 5: Clean up IO and database resources safely
                try {
                    if (writer != null) writer.close();
                    if (reader != null) reader.close();
                    if (rs != null) rs.close();
                    if (pstmt != null) pstmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException | IOException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    Key Steps & Best Practices

    • Stream Large Payloads: Avoid loading massive text or binary records entirely into memory strings; use rs.getCharacterStream() or rs.getBinaryStream() instead.
    • Chunked Writing: Reading and writing byte-by-byte or via buffer arrays ensures your application consumes negligible heap memory even with large files.
    • PreparedStatement Safety: Always use parameterized SQL statements to filter file IDs safely.
    • Thorough Cleanup: Ensure both stream readers/writers and database resources (ResultSet, Statement, Connection) are closed in the finally block.

    Related Tutorials You Might Enjoy


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

    Click the below Image to Enlarge
    JDBC : Retrieve File
    JDBC : Retrieve File
    JDBC : Retrieve File

    JDBC : Retrieve File
    JDBC : Retrieve File
    JDBC : Retrieve File

    JDBCRetriveFileDemo.java
    import java.io.FileWriter;
    import java.io.Reader;
    import java.sql.Clob;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class JDBCRetriveFileDemo
    {
        // 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 )
        {
            JDBCRetriveFileDemo jdbcRetriveFileDemo = new JDBCRetriveFileDemo();
            jdbcRetriveFileDemo.retriveFile();
        }
    
        private void retriveFile()
        {
            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_HISTORY";
    
                /*
                 * Execute the query
                 */
                preparedStatement = connection.prepareStatement(sql);
                ResultSet rs = preparedStatement.executeQuery();
    
                while( rs.next() )
                {
                    String name = rs.getString(2);
                    Clob cityHistoryClob = rs.getClob(3);
                    Reader reader = cityHistoryClob.getCharacterStream();
    
                    FileWriter fw = new FileWriter("D:/Downloads/" + name );
    
                    int i;
                    while( (i = reader.read()) != -1 )
                    {
                        fw.write((char) i);
                    }
                    System.out.println("D:/Downloads/" + name +" has saved");
                    fw.close();
                }
    
                rs.close();
    
            }
            catch( SQLException se )
            {
    
                se.printStackTrace();
            }
            catch( ClassNotFoundException e )
            {
                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
    D:/Downloads/Newyork History.txt has saved
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCRetriveFileDemoApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:
    Newer Posts Older Posts Home

    Tutorials