Storing image into database.

We can store image into database using blob field type. here is a simple example that will read image file and store it to database.

import java.sql.*;
public class insertImage{
    public static void main(String[] args) {
        System.out.println("Insert Image Example!");
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "mydatabase";
        String userName = "root";
        String password = "root";
        Connection con = null;
            con = DriverManager.getConnection(url+dbName,userName,password);
            Statement st = con.createStatement();
            File imgfile = new File("images.jpg");
            FileInputStream fin = new FileInputStream(imgfile);
            PreparedStatement pre = con.prepareStatement("insert into Image values(?,?,?)");
            System.out.println("Inserting Successfully!");
        catch (Exception e){
Image file will be stored into database and cab be retried latter as a binary stream that can be converted into image file using IO utilities. 

No comments:

Popular Posts