
how to set image in database and retrieve it using servlet(java)in msaccess

Hi Friend,
Try the following code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
InputStream sImage;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:student");
File imgfile = new File("C:/rose.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into user(name,address,image) values(?,?,?)");
pre.setString(1,"A");
pre.setString(2,"Delhi");
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select image from user where id=1");
if(rs.next()){
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
rs.close();
st.close();
con.close();
}
catch(Exception ex){
out.println("error :"+ex);
}
}
}
For the above code, we have created a table
user(id,name,address,image) id(AutoNumber) name(text) address(text) image(OLE Object)
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.