Insert an image into MySQL database using JSP page
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.
- 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`) );
- 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: http://dev.mysql.com/downloads/connector/j/5.0.html. In this tutorial we are using the mysql-connector-java-5.0.8-bin.jar file. - Creating JSP Page:
InsertImage.jsp contains the code to insert the image into MySQL database.<%@page import="java.io.InputStream"%> <%@page import="java.io.FileInputStream"%> <%@page import="java.io.File"%> <%@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> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert an Image into MySQL Database</title> </head> <body> <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 { Class.forName("com.mysql.jdbc.Driver").newInstance(); 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, "sumanth@codesuggestions.com"); 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) { ex.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (pstmt != null) { pstmt.close(); pstmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (Exception ex) { ex.printStackTrace(); } } %> </body> </html>
Leave a Comment