retrieve image from saved path java code example

Example: retrieve image from saved path java

package ImageTutorial;
 
import java.sql.*;
import java.io.*;
 
public class RetrieveImage
{
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String dburl = "jdbc:mysql://localhost/STOREDB";    
    static final String dbuser = "root";
    static final String dbpass = "root";
    
public static void main(String[] args) throws Exception, IOException, SQLException
{
 Connection con = null;
 FileOutputStream fs=null;
 PreparedStatement ps=null;
 
 try 
 {
     //Step 1 : Connecting to server and database
     con = DriverManager.getConnection(dburl, dbuser, dbpass);
     ps= con.prepareStatement("SELECT * FROM ITEM WHERE SavePic IS NOT NULL");
     ResultSet rset=ps.executeQuery();
     	    
     byte b[];
     Blob blob;
     int i=1;
     while(rset.next())
     {
      i++;
      System.out.print("ID: " + rset.getInt(1));
      System.out.print(" Product : "+rset.getString(2));
      System.out.println(" Price : "+rset.getString(3));
      
      File f=new File("/home/prashant/Documents/image/mainjava " + i + ".jpg");
     fs=new FileOutputStream(f);
      blob=rset.getBlob("SavePic");
      b=blob.getBytes(1, (int)blob.length());
      fs.write(b);
     }
 } 
 
 catch (SQLException e) 
 {
     System.err.println("Cannot connect ! ");
     e.printStackTrace();
 }
 
 finally {
     System.out.println("Closing the connection.");
     ps.close();
     fs.close();
     if (con != null) try { con.close(); } catch (SQLException ignore) {}
 }
 
}
}

Tags:

Misc Example