In this tutorial I am going to explain how to insert an image into MySQL database through JSP (Java Server Page). For this you have to table in MySQL Database.

  1. Create the Table in MySQL Database:
    CREATE TABLE image (             
           id int(5) NOT NULL auto_increment,  
           firstname varchar(25) default NULL,      
           lastname varchar(20) default NULL,      
           image blob,                         
           email varchar(50) default NULL,     
           PRIMARY KEY  (`id`)                   
  2. Configuring the JDBC Drivers:
    To connect MySQL database from Java/ JSP we need to have the MySQL JDBC Drivers. Download the jar from the following link: In this tutorial we are using the mysql-connector-java-5.0.8-bin.jar file.
  3. Creating JSP Page:
    InsertImage.jsp contains the code to insert the image into MySQL database.

    <%@page import=""%>
    <%@page import=""%>
    <%@page import=""%>
    <%@page import="java.sql.DriverManager"%>
    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.PreparedStatement"%>
    <%@page import="java.sql.Connection"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Insert an Image into MySQL Database</title>
            <h1>Insert an Image into MySQL Database!</h1>
                Connection conn = null;
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                String url = "jdbc:mysql://localhost:3306/test";//Here the "test" is the Database name
                FileInputStream fis = null;
                try {
                    conn = DriverManager.getConnection(url, "root", "");
                    File image = new File("C:/Users/chinny/Desktop/images.jpg");
                    pstmt = conn.prepareStatement("insert into image(firstname, lastname, image, email) " + "values(?,?,?,?)");
                    pstmt.setString(1, "Sumanth");
                    pstmt.setString(2, "Garakarajula");
                    pstmt.setString(4, "");
                    fis = new FileInputStream(image);
                    pstmt.setBinaryStream(3, (InputStream) fis, (int) (image.length()));
                    int count = pstmt.executeUpdate();
                    if (count > 0) {
                        System.out.println("The image has been inserted successfully");
                    } else {
                        System.out.println("The image did not insert successfully");
                } catch (Exception ex) {
                } finally {
                    try {
                        if (rs != null) {
                            rs = null;
                        if (pstmt != null) {
                            pstmt = null;
                        if (conn != null) {
                            conn = null;
                    } catch (Exception ex) {