© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
Quick Links
Easy Studies

Insert image into Table Using Java


This example illustrates the process of inserting image into database table using Servlet. This type of program is useful in social networking or HR application where it is necessary to save the uploaded photograph of the user. If the image is stored in the database you can easily retrieve using JDBC program.

In this program using FileInputStream object input image is read from the specified path. In database, the table is created with two fields’ imageid and image. Image field is declared as the Blob type to store the mage. setBinaryStream () mehod is to set an image into the field and it uses the available () method to return the number of bytes that can be read from this input stream without blocking. PreparedStatement interface is used to execute the SQL command. A SQL Statement is precompiled and stored in a preparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Insert image into Table Using Java:

import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ImageInsertInTable extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Connection con=null; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:bankdomain","scott","tiger"); PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)"); File file = new File("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/web/arttilea.jpg"); FileInputStream fs = new FileInputStream(file); ps.setInt(1,8); ps.setBinaryStream(2,fs,fs.available()); int i = ps.executeUpdate(); if(i!=0){ pw.println("image inserted successfully"); } else{ pw.println("problem in image insertion"); } } catch (Exception e){ System.out.println(e); } } }

Sample ScreenShot:

SLogix Student Projects

⇓Student Projects⇓
⇑Student Projects⇑