Tuesday, January 09, 2007

Storing Files in Database

This class lets you store files in Database. This example works for MySQL. SQL to create the table

CREATE TABLE blobtable (
filename varchar(20) NOT NULL,
data blob NOT NULL,
PRIMARY KEY (filename)
)



package net.gfour.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* This class handles storage of any file type into the database.
*
* @date Jan 9, 2007
* @author chandan
* @copyright (c) gfour.net
*/
public class BlobHelper {
private String sql = "insert into blobtable values(?,?)";

private Connection con = null;

/**
* Main method tests the usage of the class.
*/
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "admin");
BlobHelper bh = new BlobHelper();
// path of the file to be stored
bh.insert("D:\\chandan\\My Pictures\\admin.jpg", conn);
}

public boolean insert(String fileName, Connection con) {
File file = new File(fileName);
InputStream data = null;
try {
data = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, file.getName());
pstmt.setBinaryStream(2, data, (int) file.length());
pstmt.execute();
System.out.println("Update Successful");
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}

/**
* This Constructor is capable of creating the connection to the database
*
* @param url
* @param Driver
* @param sql
*/
public BlobHelper(String url, String Driver, String sql) {
this.sql = sql;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public BlobHelper() {
// Instantiate anything if required.
}

/**
* Another overloaded insert(). Works best with constructor
* BlobHelper(String, String, String)
* @param fileName
* @return
*/
public boolean insert(String fileName) {
if (con != null)
return insert(fileName, con);
return false;
}
}

0 comments:

Post a Comment