package demo;
import java.sql.*;
import java.io.*;
import java.sql.PreparedStatement;
import java.util.*;
import oracle.jdbc.driver.*;
import oracle.sql.BLOB;
public class BlobOracle
{
private final static String hostname = "localhost";
private final static String port = "1521";
private final static String sid = "ORCL";
private final static String username = "scott";
private final static String password = "tiger";
private static String fileLocation;
private static Connection connection;
public BlobOracle()
{
}
public static void main(String[] args)
{
try
{
if (args.length == 0)
{
System.out.println("\n\n Usage demo.BlobOracle ");
System.exit(0);
}
fileLocation = args[0];
setConnection();
insertBLOB();
} catch (Exception ex)
{
ex.printStackTrace();
} finally
{
}
}
private static void setConnection() throws SQLException
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("jdbc:oracle:thin:@"+hostname+ ":"+ port +":"+ sid , username , password);
connection.setAutoCommit(false);
}
private static void insertBLOB() throws SQLException, Exception
{
BLOB blob;
File file ;
FileInputStream is;
OutputStream os;
long ts1 = System.currentTimeMillis();
PreparedStatement pstmt = connection.prepareStatement("insert into media (file_name, file_content) values (?,empty_blob())");
file = new File(fileLocation);
String fileName = file.getName();
pstmt.setString(1, fileName);
pstmt.execute();
pstmt = connection.prepareStatement("select file_content from media where file_name = ? for update");
pstmt.setString(1, fileName);
ResultSet rset = pstmt.executeQuery();
rset.next();
blob = ((OracleResultSet)rset).getBLOB("file_content");
is = new FileInputStream(file);
os = blob.setBinaryStream(0);
byte[] chunk = new byte[blob.getChunkSize()];
int i=-1;
System.out.println("Inserting the Blob");
while((i = is.read(chunk))!=-1)
{
os.write(chunk,0,i);
System.out.print('.');
}
is.close();
os.close();
pstmt.close();
long ts2 = System.currentTimeMillis();
connection.commit();
connection.close();
System.out.println("\n"+ (ts2 - ts1) +" ms" );
}
}