This is the example that stores the pdf file into SQL server image data and retrieve the data back.
package com.test;
import java.sql.*;
import java.io.*;
/**
*
* @author ajayk
*
*/
public class SavePDF
{
public static void main(String[] args)
{
Connection connection=getConnection(
"jdbc:sqlserver://192.168.10.102:1433;databaseName=pp_integration","sa","rtr");
deleteImageData(connection);
insertImage(connection,"C://Documents and Settings//ram//Desktop//install.pdf");
getImageData(connection);
}
public static Connection getConnection(String connectString,String userId, String password)
{
Connection conn=null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(
connectString, userId, password);
System.out.println("connected");
return conn;
}
catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
public static void insertImage(Connection conn,String img)
{
int len;
String query;
PreparedStatement pstmt;
try
{
File file = new File(img);
FileInputStream fis = new FileInputStream(file);
len = (int)file.length();
query = ("insert into test_blob VALUES(?)");
pstmt = conn.prepareStatement(query);
pstmt.setBinaryStream(1, fis, len);
pstmt.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void getImageData(Connection conn)
{
byte[] fileBytes;
String query;
try
{
query = "select image from test_blob";
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery(query);
if (rs.next())
{
fileBytes = rs.getBytes(1);
OutputStream targetFile=
new FileOutputStream(
"C://Documents and Settings//ram//Desktop//new.pdf");
targetFile.write(fileBytes);
targetFile.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void deleteImageData(Connection conn)
{
String query;
try
{
query = "delete from test_blob";
Statement state = conn.createStatement();
state.execute(query);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
No comments:
Post a Comment