Monday, July 18, 2011

JAVA CODE TO STORE AND RETRIEVE IMAGE IN DATABASE

///////////////////////////////////////////////////////
import java.sql.*;
import java.io.*;

class MySqlSaveImage
{
public static void main(String[] RK) throws SQLException
{

Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/mydb";
ResultSet rs = null;

PreparedStatement psmnt = null;

FileInputStream fis;

try {


Class.forName("com.mysql.jdbc.Driver");//.newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "magnet");
File image = new File("c:/Me.jpg");

psmnt = connection.prepareStatement("insert into images(image) "+ "values(?)");

fis = new FileInputStream(image);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(image.length()));

int flag= psmnt.executeUpdate();
if(flag>0)
{
System.out.println("Uploaded successfully !");
}
else
{
System.out.println("unsucessfull to upload image.");
}
}
catch (Exception ex)
{
System.out.println("Found some error : "+ex);
}
finally
{
connection.close();
psmnt.close();
}
}
}


///////////////////////////////////////////////////////////////
import java.sql.*;
import java.io.*;

public class MysqlRetrieveImage
{
public static void main(String[] rk)
{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
InputStream in=null;
OutputStream out=null;
String getImg=null;
int len=0,i,count=1,index=0;
Blob bl=null;

try
{

Class.forName("com.mysql.jdbc.Driver");//.newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","magnet");
stmt=con.createStatement();

rs=stmt.executeQuery("SELECT image FROM IMAGES");

while(rs.next())
{
out = new FileOutputStream("c:/"+count+".jpg");
getImg=rs.getString(1);
System.out.println("getImg length : "+getImg.length());
in =rs.getBinaryStream(1);
byte b[]=new byte[in.available()];
System.out.println("total bytes : "+in.available());

while((index=in.read(b))!=-1)
{
out.write(b,0,index);
}
count++;
}

in.close();
out.close();
System.out.println("Images Retrieved Successfully.....");

}catch(Exception e)
{
System.out.println("Error : "+e);
}
}

}



////////////////////////////////////////////////////////////////////////////////////

/* Copy your MySql Connector .jar file into "C:\Program Files\Java\jdk1.6.0_06\jre\lib\ext" location or set the classpath for the same .jar file*/
/* Create one user into your MySql Server or use the default user name and password (username="root password="root") */
////////////////////////////////////////////////////////////////////////////////////

LEAVE YOUR COMMENTS FRIENDS.
Thank You.

1 comment: