Saturday, April 18, 2009

Inserting Images into MySQL database using Java Console Application

Hi again. Here we see insertion of image files(here jpg file, it need not be jpg all the time, you can insert any other files also) into a MySQL database.

First create the table in the MySQL database. Issue the following SQL query to create a table by the name "Image" that stores the images which we intend.

CREATE TABLE `image` ( `id` varchar(20) NOT NULL, `size` int(11) default '0',
`image` blob NOT NULL ) ENGINE=InnoDB;

We use the "File" and "FileInputStream" class to store the parameters related to the image file and then use the method "setBinaryStream(int index, FileInputStream object, int length_of_the_file)" to insert the image into the database.

The program in java is as follows(u need to have all the JDBC drivers configured before running this java app):


  1. Nice work...Easy to understand...

  2. @Teja:

    One should use the code inside your java class main method in JSP. I am no expert on JSP, but i know one thing you have to write the code in main inside scriptlet tags.

    Also one should note that we can write
    System.out.println, create a object for output stream (whatever it might be) and write to it.

    like in
    String driverName = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://localhost:3306/";

    String dbName = "test";

    String userName = "root";

    String password = "root";

    Connection con = null;



    con = DriverManager.getConnection(url+dbName,userName,password);

    Statement st = con.createStatement();

    File imgfile = new File("db.JPG");
    //give the path to the file if the file
    // is not in the same folder as the source file

    FileInputStream fin = new FileInputStream(imgfile);

    PreparedStatement pre =
    con.prepareStatement("insert into Image values(?,?,?)");

    System.out.println("Successfully inserted the file into the database!");
    //close the prepared statement
    //now close the connection
    catch (Exception e1)

  3. Hi this is Muni,

    I need a code for how to retrieve image from database
    with certain height and width , can u please send this code to my mail

    thanks & regards


  4. @Muni: Along with the above mentioned table add 2 columns of type "INT". Write a query to filter queries according to width and height.