How to store files in mysql database using JSP?

I'm developing an online recruitment system using JSP in server side. For the users who registers in it, I want them to upload their cv's from the web site so that I can store it in the database..I'm using mysql as the db..
Can I know how to do it.?..or else is there any better way of doing that?
Need a quick reply..Tx

The best way to put data in a database in a JSP is to not do it. Instead, use a Servlet that calls a DataAccessObject. The DAO puts the data in the DB and the servlet gives the data to the DAO. The JSP does nothing but display results.
Take a google for JSP MVC and DAO. BalusC has a great example of DAO and a JSP that uses one on his blog.

Similar Messages

  • How to store file content in database??????

    how to store file in database and retrived

    How to use Google to search for answers to questions that have been asked literally thousands of times previously??????
    How to post into the correct forum???????
    How to use less punctuation??????

  • Inserting a pdf file in mysql database using jdbc

    hi guys,
    i'm developing an application, where i have to upload the documents and store it in the database.
    i'm using mysql db. using the jdbc statements i have stored the contents of the pdf file. But, i'm unable to read the content, it's looks like junk values. and when i retrieved using the stream objects. it looks like the same.
    i'm able to store and retrieve the text based and image files.
    is it possible to store pdf and word documents in the database columns directly??
    any ideas are appreciated.
    thanks in advance,
    -bala

    This may help[
    Table example
    DROP TABLE IF EXISTS `employeephoto`;
    CREATE TABLE `employeephoto` (
    `Employee_ID` varchar(15) NOT NULL default '',
    `Binary_Photo` mediumblob NOT NULL,
    `LastUser` varchar(100) NOT NULL default '',
    `LastMod` datetime NOT NULL default '0000-00-00 00:00:00',
    `Created` datetime NOT NULL default '0000-00-00 00:00:00',
    PRIMARY KEY (`Employee_ID`)
    ) TYPE=MyISAM;
    Save photo as jpeg to database
    public static void saveMySqlPhoto(String empID, ImageIcon icon) {
      try {
        Image image = icon.getImage();
        BufferedImage bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
        Graphics bg = bImage.getGraphics();
        bg.drawImage(image,0,0,null);
        bg.dispose();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bImage,"jpeg",out);
        byte[] buf = out.toByteArray();
        // setup stream for blob
        ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
        // get or create a connection here
        Connection photoConnection = startup.connectionPool.getConnection();
        sqlStatement = "insert into employeephoto (Employee_ID,Binary_Photo,LastUser,LastMod,Created) values ('"+empID+"', ?, '"+startup.User+"', NOW(), NOW())";
        ps = photoConnection.prepareStatement(sqlStatement);
        ps.setBinaryStream(1,inStream,inStream.available());
        ps.executeUpdate();
        // release or close connection here
        startup.connectionPool.releaseConnection(photoConnection);
      catch (Exception exc) {
        // process error
    }Retrieve photo from database
    public static ImageIcon getMySqlPhoto(String employeeID){
      ImageIcon dPhoto = null;
      // get or create a connection here
      Connection photoConnection = connectionPool.getConnection();
      String sqlStatement = "select Binary_Photo from employeephoto where Employee_ID = '"+employeeID+"'";
      try {
        ResultSet rs = photoConnection.createStatement().executeQuery(sqlStatement);
        if (rs.next()){
          Blob image = rs.getBlob("Binary_Photo");
          // setup the streams
          InputStream input = image.getBinaryStream();
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          // set read buffer size
          byte[] rb = new byte[1024];
          int ch = 0;
          // process blob
          while ((ch=input.read(rb)) != -1){
            output.write(rb, 0, ch);
          byte[] b = output.toByteArray();
          input.close();
          output.close();
          // load final buffer
          dPhoto = new ImageIcon(b);
        rs.close();
      catch (Exception exc) {
        // do error processing
      // release or close connection here
      connectionPool.releaseConnection(photoConnection);
      return dPhoto;
    public byte[] toByteArray(int width, int height, BufferedImage imageBuff) throws java.io.IOException{
      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      bi.getGraphics().drawImage(imageBuff, 0, 0, null);
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
      param.setQuality(1.0f, false);
      encoder.setJPEGEncodeParam(param);
      encoder.encode(bi);
      return out.toByteArray();
    }rykk

  • How to insert data into mysql database using GUI?

    HI there,
    I have created a GUI application using Netbeans 6.7.1 in which there are three jtextfields. Now from those text fields i have to insert data in the mysql database. I have already connected to mysql using drivers and URL which is used to connect to DB. So what code should i write in the source of these text fields. Please help me and give the code to it.
    I actually don't know what code to be written in the source of a text field.
    Thank You.

    Yo buddy i didn't mean that. I wanted to say that if you see my project then it will be easy for you to help me. okay have a look at this code and tell me i have just created my gui
    This is Main.java -->
    package bookdatabase2;
    import java.sql.*;
    import java.awt.*;
    import javax.swing.*;
    * @author Mohd Azeem
    public class Main {
    * @param args the command line arguments
    public static void main(String[] args)throws Exception {
    // TODO code application logic here
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/books","root","");
    //PreparedStatement state=con.prepareStatement("select * from titles");
    //ResultSet result=state.executeQuery();
    //while(result.next()){
    // System.out.println(result.getString(1)+" "+result.getString(2)+" "+result.getString(3)+" "+result.getString(4));
    This the gui i have created
    BookDatabase.java -->
    package my.bookdatabase;
    import java.sql.*;
    import javax.swing.*;
    public class BookDatabase extends javax.swing.JFrame {
    public BookDatabase()throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/books","root","");
    initComponents(); }
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    public static void main(String args[])throws Exception {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    try{
    new BookDatabase().setVisible(true);}
    catch(Exception e){}
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    // End of variables declaration
    Now tell me what to do?
    i have only created the gui but unable to run it
    when i click on run only main.java is being executed
    but bookdatabase.java is not getting executed?
    what should i do please help?

  • How to write files on Client Machine using JSP

    Hi,
    I am new to JSP. Please tell me how do i write files on Client machine thru a Browser.
    Please let me know at the Earliest.
    Thanks.
    Mehul Dave

    1) Well I find it rather convenient to deploy a web app as just one file rather than a bunch of files. For deployment it's much better. However I prefer using expanded files when developping (to use auto reload in Tomcat for example)
    2) It is a bad idea to upload files inside your webapp's context (ie: in it's deployment directory) because one day an uninformed system administrator might come and redeploy the web app and therefore delete all your uploaded files (believe me, I've already experienced this!)
    What i do usually is upload it in a completely different directory, something like /uploaded_files. Your uploaded files are therefore completely independant from your webapp
    However it is a bit trickyer to get those files back. Let's take the example of image uploads. You have 2 ways of proceeding:
    - the easiest : configure your web server (apache etc...) to redirect a certain url to your external directory. For example the /upload url will point to a /uploaded_files directory. This is easier to do and the fastest way to serve images but not always the best solution: you are dependant on the web server's configuration and you can't control the visibility on your files (no security constraints, anyone can see your uploaded files if they know the url).
    - you can also write a servlet which will load the file as an array of bytes and send it back in the response.
    You can call it this way :
    <img src="/serlvets/showmyimage?path=uploaded.gif">
    in this way you can control your uploaded files better: you may want to define security constraints on the visibity or not of uploaded files depending on the user which has logged on the site.

  • How to verify if user already exists in MySQL database using JSP?

    Hi, I am trying to create a website that allows users to register and then login. All regsitration details are stored in a MySQL table and I am attempting to have a java bean check that a new user does not already exist by looking up the username. However, I cannot get this to work, the bean is allowing anyone through. I believe there may be a problem with my while loop as the bean checks through the stored usernames in the database. Any suggestions appreciated thanks. See my code below:[
    code]package foo;
    import java.sql.*;
    import java.util.*;
    public class FormBean {
         private String firstName;
         private String lastName;
         private String email;
         private String userName;
         private String password1;
         private String password2;
         private Hashtable errors;
         public boolean validate() {
              boolean allOk=true;
              if (firstName.equals("")) {
                   errors.put("firstName","Please enter your first name");
                   firstName="";
                   allOk=false;
              if (lastName.equals("")) {
                   errors.put("lastName","Please enter your last name");
                   lastName="";
                   allOk=false;
              if (email.equals("") || (email.indexOf('@') == -1)) {
                   errors.put("email","Please enter a valid email address");
                   email="";
                   allOk=false;
              if (userName.equals("")) {
                   errors.put("userName","Please enter a username");
                   userName="";
                   allOk=false;
    try {
              String database = "******hidden******";
              Class.forName("com.mysql.jdbc.Driver");
              Connection conn = DriverManager.getConnection(database,"********hidden*******");
              Statement stat = conn.createStatement();
              String query="SELECT u_name FROM users;";
              String DbUserName="";
              ResultSet rst=stat.executeQuery(query);
              while(rst.next()) {
    DbUserName=rst.getString("u_name");
    if (userName.equals(DbUserName)) {
    allOk=false;
    errors.put("userName","User name already exists, please choose another");
    userName="";
    conn.close();
    break;
    } catch (Exception ex) {
    ex.printStackTrace();
              if (password1.equals("") ) {
                   errors.put("password1","Please enter a valid password");
                   password1="";
                   allOk=false;
              if (!password1.equals("") && (password2.equals("") || !password1.equals(password2))) {
                   errors.put("password2","Please confirm your password");
                   password2="";
                   allOk=false;
    return allOk;
         public String getErrorMsg(String s) {
              String errorMsg =(String)errors.get(s.trim());
         return (errorMsg == null) ? "":errorMsg;
         public FormBean() {
         firstName="";
         lastName="";
         email="";
    userName="";
         password1="";
         password2="";
         errors = new Hashtable();
         public String getFirstName() {
              return firstName;
         public String getLastName() {
              return lastName;
         public String getEmail() {
              return email;
         public String getUserName() {
              return userName;
         public String getPassword1() {
              return password1;
         public String getPassword2() {
              return password2;
         public void setFirstName(String fname) {
              firstName =fname;
         public void setLastName(String lname) {
              lastName =lname;
         public void setEmail(String eml) {
              email=eml;
         public void setUserName(String u) {
              userName=u;
         public void setPassword1(String p1) {
              password1=p1;
         public void setPassword2(String p2) {
              password2=p2;
         public void setErrors(String key, String msg) {     
              errors.put(key,msg);

    Hmm, tried that and now have more build errors in the finally section.
    init:
    deps-jar:
    Compiling 1 source file to C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\build\classes
    C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:57: cannot resolve symbol
    symbol  : variable rst
    location: class foo.FormBean
                if (rst != null) rst.close();
    C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:57: cannot resolve symbol
    symbol  : variable rst
    location: class foo.FormBean
                if (rst != null) rst.close();
    C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:58: cannot resolve symbol
    symbol  : variable stat
    location: class foo.FormBean
                if (stat != null) stat.close();
    C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:58: cannot resolve symbol
    symbol  : variable stat
    location: class foo.FormBean
                if (stat != null) stat.close();
    C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:59: cannot resolve symbol
    symbol  : variable conn
    location: class foo.FormBean
                if (conn != null)  conn.close();
    C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:59: cannot resolve symbol
    symbol  : variable conn
    location: class foo.FormBean
                if (con != null)  conn.close();
    6 errors
    BUILD FAILED (total time: 1 second)Just for a quick test, I deleted the sql exception and finally code and replaced it with a regular exception just to see what happened and got no build errors, however when I run the form I am getting an sql exception from the prepared statement, parameter out of range (1 > 0). I tried reading into prepared statements, and although I now understand their basics, I still have no idea why I'm getting this error?

  • How to connect to the mysql database using applet from remote PC

    Hii All..
    I am also facing a problem.
    My web server and mysql server are running on the same PC.
    when i connect to the database from the same PC.
    Its connection but when i am trying to connect to the database from the different PC its giving error and not finding the driver "com.mysql.jdbc.Driver" because this is there on the server PC and applet runs on the client side..
    So to load the deriver on the client side so that it can run the applet to make the database connection on the remote PC.
    Thanks
    Uttam

    You are missing the library on the client.
    It must be moved to the client.
    Just like any other library that an applet requires.
    And that has nothing to do with JDBC.
    There are certainly way(s) to do it. Perhaps a forum that addresses applets, web usage or guis would provide an answer.

  • Urgent, Please help !!! Input Date field in Mysql database using JSP

    Hi All,
    Please help me ! I am trying to store a date field in MySql databaseusing JSP on Tomcat Server.I am gettting the following error.
    I am taking the String Input and then trying to convert it into date type
    inorder to store it into date field in a database.
    I am using the following code :
    <%
    try{
    String dt=request.getParameter("avldt");
    SimpleDateFormat adt= new SimpleDateFormat("dd-MM-yyyy");
    Date sqlToday = new java.sql.Date(adt.parse(dt).getTime());
    catch(ParseException e){
         e.printStackTrace();
    %>
    But I am getting the following error message :
    Class jsp.myjsp.SimpleDateFormat not found.
    Please help me !!!.It's very urgent.
    Thanks,
    Savdeep

    programming is more then copy pasting, it actually is usefull to think about what you are doing. First you declare that you date is format dd-MM-yyyy, then you want to parse a date in format dd/MM/yyyy and behold Java warns you it cannot parse the one into the second ! Cant you solve the rest of this puzzle yourself then ?

  • How to check files in the directory using JSP?.

    Hi,
    How can i check the file is directory or file and readable or writable and file size and type of file(Ex. jpg, txt, doc., etc). i want to list the specific type of file in the particular directroy.. please help me..
    Regards
    CHinna

    With the File class, using the methods isFile(), isDirectory(), canRead(), canWrite(), length() and getName()
    With File.listFiles() you can get a directory listing. If you want to limit the amount of files returned, you can pass your own FileFilter to it.
    http://java.sun.com/javase/6/docs/api/java/io/File.html

  • Accesing the mysql database using jsp

    hi. I'm trbing to access the mysal data base using the following jsp code. but it gives me the exception: Exception is: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    please help.
    <%@ page language="java" import="java.sql.*" %>
    <%
         String JDBC_DRIVER = ("com.mysql.jdbc.Driver");
         String DATABASE_URI = ("jdbc:mysql://localhost/MCQTest?user=root&password=vishanka" );
         Connection con=null;
         ResultSet rst=null;
         Statement stmt=null;
         int noOfQuestions = 30;
         String [] question = new String [noOfQuestions];
         try
              Class.forName(JDBC_DRIVER).newInstance();
              con=DriverManager.getConnection(DATABASE_URI);
              stmt=con.createStatement();
              rst = stmt.executeQuery("select question from question");
              while(rst.next())
                   for(int i = 1; i<=noOfQuestions; i++)
                        question[i-1] = rst.getString(i);
                        out.print(question[i-1]);
              rst.close();
              stmt.close();
              con.close();
         catch(Exception ex)
              {out.println("Exception is: " + ex.toString());ex.printStackTrace();}
    %>
    <html>
    <head><title>StudentRegistration Front</title></head>
    <jsp:useBean id="user" class="beans.User" scope="session" />
    <body>
    <font color="blue">
    <h2 align="center">
    <p>Welcome <jsp:getProperty name="user" property="name" />:
    </h2>
    </font>
    <form action="marking.jsp" method="post">
    <h4 align="center">
    <input type="submit" value="submit">
    </h4>
    </form>
    </font>
    </body>
    </html>

    sorry guys. the code is given below clearly.
    <%@ page language="java" import="java.sql.*" %>
    <%
         String JDBC_DRIVER = ("com.mysql.jdbc.Driver");
         String DATABASE_URI = ("jdbc:mysql://localhost/MCQTest?user=root&password=vishanka" );
         Connection con=null;
         ResultSet rst=null;
         Statement stmt=null;
         int noOfQuestions = 30;
         String [] question = new String [noOfQuestions];
         try
              Class.forName(JDBC_DRIVER).newInstance();
              con=DriverManager.getConnection(DATABASE_URI);
              stmt=con.createStatement();
              rst = stmt.executeQuery("select question from question");
              while(rst.next())
                   for(int i = 1; i<=noOfQuestions; i++)
                        question[i-1] = rst.getString(i);
                        out.print(question[i-1]);
              rst.close();
              stmt.close();
              con.close();
         catch(Exception ex)
              {out.println("Exception is: " + ex.toString());ex.printStackTrace();}
    %>
    <html>
    <head><title>StudentRegistration Front</title></head>
    <jsp:useBean id="user" class="beans.User" scope="session" />
    <body>
      <font color="blue">
      <h2 align="center">
        <p>Welcome <jsp:getProperty name="user" property="name" />:
      </h2>
      </font>
      <form action="marking.jsp" method="post">
         <h4 align="center">
             <input type="submit" value="submit">
        </h4>
      </form>
      </font>
    </body>
    </html>

  • Populating my dropdown menu from MySQL database using jsp

    I my database i have a table of users and i want everytime a user is added the dropdown menu gets updated, this is make updating of user's profile easy. I tried the one bellow but still get me 80 errors:
    ----connection String------
    <select name="userName" id="userName">
    <% for(int i=1; i<=resultsList; ++i){%>
    <option value="<%=out.println(rs.getUserName(1))%>"><%=out.println(rs.getUserName(1))%></option>
    <option value="<%=out.println(rs.getUserName(i))%>"><%=out.println(rs.getUserName(i))%></option>
    <%}%>
    </select>
    Pls i need help

    80 errors, you say?
    I'm not a fan of writing muddled jsp pages that refer to the database layer. If you're willing to learn JSF or some other web framework, you'll being able to write better code and never use a scriptlet again.

  • Error in connecting to mysql database using jsp

    Hi
    I've encountered this error:
    java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver
    while trying to connect to MySQL db.
    I've downloaded the driver from www.mysql.com, and set the classpath as: "C:\mm.mysql.jdbc-1.2b;%CLASSPATH%;"
    But it juz doesn't seem to work...
    Can someone pls help me?

    These are my settings in autoexec.bat:
    SET PATH=C:\PROGRA~1\ABRIAS~1\ABRIAS~1\PERL\BIN;%PATH%;
    SET JAVA_HOME=C:\jdk1.3.1
    SET TOMCAT_HOME=C:\Tomcat3.2.3
    SET CLASSPATH=C:\mm.mysql.jdbc-1.2b;%CLASSPATH%;
    Well, i'm quite new to jsp so i'm not sure what u meant by "In the servlet container's init scripts?". I onli did the settings above and reset my server.
    I've tried checking the dir...and yes there's a dir named org.
    Any ideas wat can possibly be wrong???

  • Uploading a file into mySQL database?

    Hello, everybody.
    Can anyone give me a code snippet or at least a hint, how could I upload a file into the BLOB field of mySQL database using JSP webpage? How do you generally store uploaded files on the server? If anyone could suggest a good algorythm of saving the files in the server's file system and saving only their URLs in the database (this was my initial idea), I would be ready to accept this as well.
    Would be appreciated for any help.

    Hi
    Fou uploading the files from client site to server user the utility given by oreilly Go to this site and down the code for uploading the source code for fileupload
    For writing this code to database use this code
    code
    import java.sql.*;
    import java.io.*;
    class BlobTest {
         public static void main(String args[]) {
              try {
                   //File to be created. Original file is duke.gif.
                   DriverManager.registerDriver( new org.gjt.mm.mysql.Driver());
                   Connection conn = DriverManager.getConnection("jdbc:mysql://agt_229/test","manoj","manoj");
                   /*PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobTest VALUES( ?, ? )" );
                   pstmt.setString( 1, "photo1");
                   File imageFile = new File("duke.gif");
                   InputStream is = new FileInputStream(imageFile);
                   pstmt.setBinaryStream( 2, is, (int)(imageFile.length()));
                   pstmt.executeUpdate();
                   PreparedStatement pstmt = conn.prepareStatement("SELECT image FROM testblob WHERE Name = ?");
                   pstmt.setString(1, args[0]);
                   RandomAccessFile raf = new RandomAccessFile(args[0],"rw");
                   ResultSet rs = pstmt.executeQuery();
                   if(rs.next()) {
                        Blob blob = rs.getBlob(1);
                        int length = (int)blob.length();
                        byte [] _blob = blob.getBytes(1, length);
                        raf.write(_blob);
                   System.out.println("Completed...");
              } catch(Exception e) {
                   System.out.println(e);
    end of code
    this code contain both inserting into table and retrieving from table

  • How to store file content in BLOB field MySql database using java

    Hi!
    i want to store the file content in a BLOB field in MySql database using java.
    Please help me out..........
    thanx in advance...
    bye

    i stored images in db, and retrieved them. like that cant i store pdf file in db, and retrieve it back using oracle db?
    Plz help me out how to put a file in db. i need complete code. thanks in advance.

  • How To Store pdf or doc file in Oracle Database using Java Jdbc?

    can any one help me out How To Store pdf or doc file in Oracle Database using Java Jdbc in JSP/Serlet? i tried like anything. using blob also i tried. but i am able 2 store images in DB not files. please if u know or else if u have some code like this plz send that to me, and help me out plz. i need that urgent.

    Hi.. i am not getting error, But i am not getting the original contents from my file. i am getting all ASCII vales, instead of my original data. here i am including my code.
    for Adding PDF in DB i used image.jsp
    Database table structure (table name. pictures )
    Name Null? Type
    ID NOT NULL NUMBER(11)
    IMAGE BLOB
    <%@ page language="java" import="java.util.*,java.sql.*,java.io.*" pageEncoding="ISO-8859-1"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%
    try{
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
         PreparedStatement ps,pstmt,psmnt;
         ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
    File file =
    new File("D:/info.pdf");
    FileInputStream fs = new FileInputStream(file);
    ps.setInt(1,4);
    ps.setBinaryStream(2,fs,fs.available());
    int i = ps.executeUpdate();
    if(i!=0){
    out.println("<h2>PDF inserted successfully");
    else{
    out.println("<h2>Problem in image insertion");
    catch(Exception e){
    out.println("<h2>Failed Due To "+e);
    %>
    O/P: PDF inserted successfully
    i tried to display that pdf using servlet. i am giving the code below.
    import java.io.IOException;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class DispPDF extends HttpServlet {
         * The doGet method of the servlet. <br>
         * This method is called when a form has its tag value method equals to get.
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         public void service(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              //response.setContentType("text/html"); i commented. coz we cant use response two times.
              //PrintWriter out = response.getWriter();
              try{
                   InputStream sPdf;
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
                        PreparedStatement ps,pstmt,psmnt;
                   psmnt = con.prepareStatement("SELECT image FROM pictures WHERE id = ?");
                        psmnt.setString(1, "4"); // here integer number '4' is image id from the table.
                   ResultSet rs = psmnt.executeQuery();
                        if(rs.next()) {
                   byte[] bytearray = new byte[1048576];
                        //out.println(bytearray);
                        int size=0;
                        sPdf = rs.getBinaryStream(1);
                        response.reset();
                        response.setContentType("application/pdf");
                        while((size=sPdf.read(bytearray))!= -1 ){
                        //out.println(size);
                        response.getOutputStream().write(bytearray,0,size);
                   catch(Exception e){
                   System.out.println("Failed Due To "+e);
                        //out.println("<h2>Failed Due To "+e);
              //out.close();
    OP
    PDF-1.4 %âãÏÓ 2 0 obj <>stream xœ+är á26S°00SIá2PÐ5´1ôÝ BÒ¸4Ü2‹ŠKüsSŠSŠS4C²€ê P”kø$V㙂GÒU×713CkW )(Ü endstream endobj 4 0 obj <>>>/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000325 00000 n 0000000015 00000 n 0000000413 00000 n 0000000168 00000 n 0000000464 00000 n 0000000509 00000 n trailer <<01b2fa8b70ac262bfa939cc786f8770c>]/Root 5 0 R/Size 7/Info 6 0 R>> startxref 641 %%EOF
    plz help me out.

Maybe you are looking for