Inserting Image in MySql Database Table
Consider a case where we want that along with the name of the person and its information, his image should also come with all these things. After going through this tutorial you can better understand the concept of inserting a image in the database table, so go through this example properly.
To get the program working we need to use a doGet() method to write our business logic as it is server side programming so all the processing will be done by the container. First of all make a class named JdbcInsertImage, the name of the class should be such that the person can understand what the program is going to do. This class must extend the HttpServlet class which is an abstract method. Now inside the doGet() method call the method getWriter() of the class PrintWriter. To insert a image from our java program we need to make a connection between our java class and the MySql database which we are using. After the connection establishment we will pass a insertion query for the image in the prepareStatement() method of the Connection object which returns the PreparedStatement object. Note that the data type for the image we have used is mediumblob. It is case sensitive.
As we have to insert an image file in our database so there is a need to use a File class of the java.io package. In the constructor of the File class pass the path of the file. To read the image file we will use FileInputStream class. To set the image in the database use the method setBinaryStream() of the PreparedStatement interface. If the image will be inserted in the database you will get the message "image has been inserted" otherwise "image is not inserted".
The code of the program is given below:
import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class JdbcInsertImage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost:3306/roseindia"; java.sql.Connection connection=null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "root", "root"); PreparedStatement pst = connection.prepareStatement ("insert into image values(?,?)"); File file = new File("C:/apache-tomcat-5.5.20/webapps /mywork/grad_sm.gif"); FileInputStream fis = new FileInputStream(file); pst.setBinaryStream(1,fis,fis.available()); pst.setString(2, "Tim"); int i = pst.executeUpdate(); if(i!=0) { pw.println("image has been inserted"); } else { pw.println("image is not inserted"); } } catch (Exception e) { System.out.println(e); } } } |
The output of the program is given below: