Saturday, 23 August 2014

JDBC : Store File

🚀 Master Java database programming and file handling hands-on!

🔔 Subscribe to Ram N Java on YouTube

Storing Files in Databases Using JDBC

In real-world applications, you often need to persist file data—such as text documents, configuration files, or logs—directly into relational database tables.

Relational databases like MySQL support Large Object data types such as CLOB (Character Large Object) and TEXT / LONGTEXT for storing large text files. With JDBC's PreparedStatement and Java I/O character streams (such as FileReader), you can stream and save large files directly into your database efficiently.

Database Table Structure

Before running the Java program, create the destination table in MySQL to hold your file and its metadata:

CREATE TABLE `city_history` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `city_name` VARCHAR(100) NOT NULL,
  `history` LONGTEXT,
  PRIMARY KEY (`id`)
);

Java Program: Storing a File Using PreparedStatement

Here is the complete Java code that reads a local file using FileReader and streams its content into MySQL using setCharacterStream():

package com.ram.jdbc;

import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class StoreFileDemo {

    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) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        FileReader reader = null;

        try {
            // Load MySQL Driver & Open Connection
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            String sql = "INSERT INTO city_history (city_name, history) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);

            // Set city name parameter
            pstmt.setString(1, "New York");

            // Locate file and read via FileReader
            File file = new File("history.txt");
            reader = new FileReader(file);

            // Stream file content into database column
            pstmt.setCharacterStream(2, reader, (int) file.length());

            int rowsInserted = pstmt.executeUpdate();
            System.out.println("File stored successfully! Rows inserted: " + rowsInserted);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) reader.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

Key Takeaways

  • setCharacterStream() allows you to stream character data directly to the database without loading massive files completely into application memory.
  • For binary files (like images, audio, or PDFs), use setBinaryStream() with FileInputStream and BLOB column types.
  • Always properly close the FileReader, PreparedStatement, and Connection to avoid file locks and database leaks.

Related Tutorials You Might Enjoy


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

Click the below Image to Enlarge
JDBC : Store File
JDBC : Store File
JDBC : Store File
JDBC : Store File
JDBC : Store File
JDBCStoreFileDemo.java
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCStoreFileDemo
{
    // 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)
    {
        JDBCStoreFileDemo jdbcStoreFileDemo = new JDBCStoreFileDemo();
        jdbcStoreFileDemo.storeFile();
    }

    private void storeFile()
    {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        FileReader fileReader = 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 = "insert into CITY_HISTORY values(?,?,?);";

            preparedStatement = connection.prepareStatement(sql);

            File file = new File("D:/Downloads/Newyork History.txt");
            fileReader = new FileReader(file);

            preparedStatement.setInt(1, 1);
            preparedStatement.setString(2, file.getName());
            preparedStatement.setCharacterStream(3, fileReader,
                    (int) file.length());

            int numberOfRowsInserted = preparedStatement.executeUpdate();

            System.out
                    .println("numberOfRowsInserted : " + numberOfRowsInserted);

        }
        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();
            }

            if (fileReader != null)
            {
                try
                {
                    fileReader.close();
                }
                catch (IOException e)
                {

                    e.printStackTrace();
                }
            }
        }

    }
}

Output
numberOfRowsInserted : 1

SQL
CREATE TABLE `CITY_HISTORY` (  
`ID` int(11) NOT NULL AUTO_INCREMENT,  
`Name` char(35) NOT NULL DEFAULT '',  
`History_Details` LONGTEXT  NULL ,   
PRIMARY KEY (`ID`)) 
ENGINE=InnoDB;

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCStoreFileDemoApp Project Click the below link

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

See also:

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

    Post a Comment

    Tutorials