当前位置: 技术问答>java相关
如何可以将一个大文件存入数据库?
来源: 互联网 发布时间:2015-09-01
本文导语: 如何可以将一个大文件存入数据库? 有没有具体可参考的代码? | 给你一个例子: 插入: /* * This class is used to INSERT data into a BLOB datatype column in an Oracle8i database. * This class has...
如何可以将一个大文件存入数据库?
有没有具体可参考的代码?
有没有具体可参考的代码?
|
给你一个例子:
插入:
/*
* This class is used to INSERT data into a BLOB datatype column in an Oracle8i database.
* This class has a method called insertBlobData which takes three input parameters:
* 1) The name of the file to be added to the database
* 2) The description of the file to be added to the database
* 3) The physical path to the file, to be added to the database
* For further suggestions/improvements/help please feel free to contact me at mjauhar@usa.net
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class InsertBlob {
public InsertBlob() {
}
public static void main(String[] args) {
InsertBlob insertBlob1 = new InsertBlob();
if(args.length != 3) {
System.out.println("Usage: java InsertBlob FileName FileDescription FilePath");
System.out.println("Example: java InsertBlob myImage.jpg "File description text comes here." "C:\\MyFolder\\myImage.jpg"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement with the FOR UPDATE clause could not find a record.
* 2 ----- Indicates that file with the same name and description already exists in the database.
* 3 ----- Indicates a SQLException has occurred.
* 4 ----- Indicates a FileNotException has occurred.
* 5 ----- Indicates a some other Exception has occurred.
* 6 ----- Indicates an error has occurred in the finally block.
*/
final int output = insertBlob1.insertBlobData(args[0], args[1], args[2]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
insertBlob1 = null;
}
}
}
private static int insertBlobData(final String fileName, final String fileDescription, final String filePath) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
String query = null;
try {
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* First execute a query to see if a file with the same name and description already exists.
*/
query = "SELECT FileId FROM tblBlobDemo WHERE FileName='" + fileName + "' AND FileDescription='" + fileDescription + "' ORDER BY FileId DESC";
rs = stmt.executeQuery(query);
if(!rs.next()) {
/*
* Insert all the data, for the BLOB column we use the function empty_blob(), which creates a locator for the BLOB datatype.
* A locator is an object that ponts to the actual location of the BLOB data in the database. A locator is essential to manipulate BLOB data.
*/
query = "INSERT INTO tblBlobDemo VALUES(seqFileId.NextVal, sysdate, '" + fileName + "', empty_blob(), '" + fileDescription + "')";
stmt.execute(query);
/*
* Once the locator has been inserted, we retrieve the locator by executing a SELECT statement with the FOR UPDATE clause to manually lock the row.
*/
query = "SELECT FileData FROM tblBlobDemo WHERE FileName='" + fileName + "' AND FileDescription='" + fileDescription +
"' ORDER BY FileId DESC FOR UPDATE";
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Once a locator has been retrieved we can use it to insert the binary data into the database.
*/
BLOB blob = ((OracleResultSet)rs).getBLOB("FileData");
os = blob.getBinaryOutputStream();
final File f = new File(filePath);
is = new FileInputStream(f);
final byte[] buffer = new byte[blob.getBufferSize()];
int bytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
blob = null;
}
else {
returnValue = 1;
}
}
else {
returnValue = 2;
}
}
catch(SQLException e) {
returnValue = 3;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 4;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
query = null;
}
catch(Exception e) {
returnValue = 6;
e.printStackTrace();
}
}
return returnValue;
}
}
插入:
/*
* This class is used to INSERT data into a BLOB datatype column in an Oracle8i database.
* This class has a method called insertBlobData which takes three input parameters:
* 1) The name of the file to be added to the database
* 2) The description of the file to be added to the database
* 3) The physical path to the file, to be added to the database
* For further suggestions/improvements/help please feel free to contact me at mjauhar@usa.net
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class InsertBlob {
public InsertBlob() {
}
public static void main(String[] args) {
InsertBlob insertBlob1 = new InsertBlob();
if(args.length != 3) {
System.out.println("Usage: java InsertBlob FileName FileDescription FilePath");
System.out.println("Example: java InsertBlob myImage.jpg "File description text comes here." "C:\\MyFolder\\myImage.jpg"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement with the FOR UPDATE clause could not find a record.
* 2 ----- Indicates that file with the same name and description already exists in the database.
* 3 ----- Indicates a SQLException has occurred.
* 4 ----- Indicates a FileNotException has occurred.
* 5 ----- Indicates a some other Exception has occurred.
* 6 ----- Indicates an error has occurred in the finally block.
*/
final int output = insertBlob1.insertBlobData(args[0], args[1], args[2]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
insertBlob1 = null;
}
}
}
private static int insertBlobData(final String fileName, final String fileDescription, final String filePath) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
String query = null;
try {
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* First execute a query to see if a file with the same name and description already exists.
*/
query = "SELECT FileId FROM tblBlobDemo WHERE FileName='" + fileName + "' AND FileDescription='" + fileDescription + "' ORDER BY FileId DESC";
rs = stmt.executeQuery(query);
if(!rs.next()) {
/*
* Insert all the data, for the BLOB column we use the function empty_blob(), which creates a locator for the BLOB datatype.
* A locator is an object that ponts to the actual location of the BLOB data in the database. A locator is essential to manipulate BLOB data.
*/
query = "INSERT INTO tblBlobDemo VALUES(seqFileId.NextVal, sysdate, '" + fileName + "', empty_blob(), '" + fileDescription + "')";
stmt.execute(query);
/*
* Once the locator has been inserted, we retrieve the locator by executing a SELECT statement with the FOR UPDATE clause to manually lock the row.
*/
query = "SELECT FileData FROM tblBlobDemo WHERE FileName='" + fileName + "' AND FileDescription='" + fileDescription +
"' ORDER BY FileId DESC FOR UPDATE";
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Once a locator has been retrieved we can use it to insert the binary data into the database.
*/
BLOB blob = ((OracleResultSet)rs).getBLOB("FileData");
os = blob.getBinaryOutputStream();
final File f = new File(filePath);
is = new FileInputStream(f);
final byte[] buffer = new byte[blob.getBufferSize()];
int bytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
blob = null;
}
else {
returnValue = 1;
}
}
else {
returnValue = 2;
}
}
catch(SQLException e) {
returnValue = 3;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 4;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
query = null;
}
catch(Exception e) {
returnValue = 6;
e.printStackTrace();
}
}
return returnValue;
}
}
|
更新:
/*
* This class is used to UPDATE a BLOB datatype in an Oracle8i database.
* This class has a method called updateBlobData which takes four input parameters:
* 1) The file-id of the file to be updated in the database
* 2) The name of the new file to be added to the database
* 3) The description of the new file to be added to the database
* 4) The physical path to the new file, to be added to the database
* For further suggestions/improvements/help please feel free to contact me at mjauhar@usa.net
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class UpdateBlob {
public UpdateBlob() {
}
public static void main(String[] args) {
UpdateBlob updateBlob1 = new UpdateBlob();
if(args.length != 4) {
System.out.println("Usage: java UpdateBlob FileId NewFileName NewFileDescription NewFilePath");
System.out.println("Example: java UpdateBlob 1 myNewImage.jpg "New file description text comes here." "C:\\MyFolder\\myNewImage.jpg"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement with the FOR UPDATE clause could not find a record.
* 2 ----- Indicates that the FileName and FileDescription columns could not be updated.
* 3 ----- Indicates a SQLException has occurred.
* 4 ----- Indicates a FileNotException has occurred.
* 5 ----- Indicates a some other Exception has occurred.
* 6 ----- Indicates an error has occurred in the finally block.
*/
final int output = updateBlob1.updateBlobData(args[0], args[1], args[2], args[3]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
updateBlob1 = null;
}
}
}
private static int updateBlobData(final String fileId, final String fileName, final String fileDescription, final String filePath) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
String query = null;
try {
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* First execute a query to update the FileName, FileDescription and the FileData columns.
*/
query = "UPDATE tblBlobDemo SET FileName='" + fileName + "', FileDescription='" + fileDescription + "', FileData=empty_blob() WHERE FileId=" + fileId;
final int numberOfRecordsUpdated = stmt.executeUpdate(query);
if(numberOfRecordsUpdated == 1) {
/*
* Updating a BLOB datatype in a database involves replacing an entire BLOB and not modifying it in place.
* Since a locator has already been inserted for the BLOB datatype using the InsertBlob class.
* We retrieve the locator by executing a SELECT statement with the FOR UPDATE clause to manually lock the row.
*/
query = "SELECT FileData FROM tblBlobDemo WHERE FileId=" + fileId + " FOR UPDATE";
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Once a locator has been retrieved we can use it to insert the binary data into the database.
*/
BLOB blob = ((OracleResultSet)rs).getBLOB("FileData");
os = blob.getBinaryOutputStream();
final File f = new File(filePath);
is = new FileInputStream(f);
final byte[] buffer = new byte[blob.getBufferSize()];
int bytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
blob = null;
}
else {
returnValue = 1;
}
}
else {
returnValue = 2;
}
}
catch(SQLException e) {
returnValue = 3;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 4;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
query = null;
}
catch(Exception e) {
returnValue = 6;
e.printStackTrace();
}
}
return returnValue;
}
}
/*
* This class is used to UPDATE a BLOB datatype in an Oracle8i database.
* This class has a method called updateBlobData which takes four input parameters:
* 1) The file-id of the file to be updated in the database
* 2) The name of the new file to be added to the database
* 3) The description of the new file to be added to the database
* 4) The physical path to the new file, to be added to the database
* For further suggestions/improvements/help please feel free to contact me at mjauhar@usa.net
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class UpdateBlob {
public UpdateBlob() {
}
public static void main(String[] args) {
UpdateBlob updateBlob1 = new UpdateBlob();
if(args.length != 4) {
System.out.println("Usage: java UpdateBlob FileId NewFileName NewFileDescription NewFilePath");
System.out.println("Example: java UpdateBlob 1 myNewImage.jpg "New file description text comes here." "C:\\MyFolder\\myNewImage.jpg"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement with the FOR UPDATE clause could not find a record.
* 2 ----- Indicates that the FileName and FileDescription columns could not be updated.
* 3 ----- Indicates a SQLException has occurred.
* 4 ----- Indicates a FileNotException has occurred.
* 5 ----- Indicates a some other Exception has occurred.
* 6 ----- Indicates an error has occurred in the finally block.
*/
final int output = updateBlob1.updateBlobData(args[0], args[1], args[2], args[3]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
updateBlob1 = null;
}
}
}
private static int updateBlobData(final String fileId, final String fileName, final String fileDescription, final String filePath) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
String query = null;
try {
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* First execute a query to update the FileName, FileDescription and the FileData columns.
*/
query = "UPDATE tblBlobDemo SET FileName='" + fileName + "', FileDescription='" + fileDescription + "', FileData=empty_blob() WHERE FileId=" + fileId;
final int numberOfRecordsUpdated = stmt.executeUpdate(query);
if(numberOfRecordsUpdated == 1) {
/*
* Updating a BLOB datatype in a database involves replacing an entire BLOB and not modifying it in place.
* Since a locator has already been inserted for the BLOB datatype using the InsertBlob class.
* We retrieve the locator by executing a SELECT statement with the FOR UPDATE clause to manually lock the row.
*/
query = "SELECT FileData FROM tblBlobDemo WHERE FileId=" + fileId + " FOR UPDATE";
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Once a locator has been retrieved we can use it to insert the binary data into the database.
*/
BLOB blob = ((OracleResultSet)rs).getBLOB("FileData");
os = blob.getBinaryOutputStream();
final File f = new File(filePath);
is = new FileInputStream(f);
final byte[] buffer = new byte[blob.getBufferSize()];
int bytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
blob = null;
}
else {
returnValue = 1;
}
}
else {
returnValue = 2;
}
}
catch(SQLException e) {
returnValue = 3;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 4;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
query = null;
}
catch(Exception e) {
returnValue = 6;
e.printStackTrace();
}
}
return returnValue;
}
}
|
取出:
/*
* This class is used to select a BLOB datatype from an Oracle8i database onto the file system.
* This class has a method called selectBlobData which takes two input parameters:
* 1) The file-id of the file to be extracted from the database
* 2) The physical path to which the file must be extracted.
* For further suggestions/improvements/help please feel free to contact me at mjauhar@usa.net
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class SelectBlob {
public SelectBlob() {
}
public static void main(String[] args) {
SelectBlob selectBlob1 = new SelectBlob();
if(args.length != 2) {
System.out.println("Usage: java SelectBlob FileId FilePath");
System.out.println("Example: java SelectBlob 1 "C:\\MyFolder\\"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement could not find a record.
* 2 ----- Indicates a SQLException has occurred.
* 3 ----- Indicates a FileNotException has occurred.
* 4 ----- Indicates a some other Exception has occurred.
* 5 ----- Indicates an error has occurred in the finally block.
*/
final int output = selectBlob1.selectBlobData(args[0], args[1]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
selectBlob1 = null;
}
}
}
private static int selectBlobData(final String fileId, final String path) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
BLOB blob = null;
try {
final String query = "SELECT FileName, FileData FROM tblBlobDemo WHERE FileId = " + fileId;
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* Execute the SELECT statement
*/
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Extract the BLOB data to a file on the local file system.
*/
blob = ((OracleResultSet)rs).getBLOB("FileData");
is = blob.getBinaryStream();
final String fileName = rs.getString("FileName");
final String filePath = path + fileName;
os = new FileOutputStream(filePath);
final int bufferSize = blob.getBufferSize();
final byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
else {
returnValue = 1;
}
}
catch(SQLException e) {
returnValue = 2;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 3;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 4;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
blob = null;
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
}
return returnValue;
}
}
/*
* This class is used to select a BLOB datatype from an Oracle8i database onto the file system.
* This class has a method called selectBlobData which takes two input parameters:
* 1) The file-id of the file to be extracted from the database
* 2) The physical path to which the file must be extracted.
* For further suggestions/improvements/help please feel free to contact me at mjauhar@usa.net
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class SelectBlob {
public SelectBlob() {
}
public static void main(String[] args) {
SelectBlob selectBlob1 = new SelectBlob();
if(args.length != 2) {
System.out.println("Usage: java SelectBlob FileId FilePath");
System.out.println("Example: java SelectBlob 1 "C:\\MyFolder\\"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement could not find a record.
* 2 ----- Indicates a SQLException has occurred.
* 3 ----- Indicates a FileNotException has occurred.
* 4 ----- Indicates a some other Exception has occurred.
* 5 ----- Indicates an error has occurred in the finally block.
*/
final int output = selectBlob1.selectBlobData(args[0], args[1]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
selectBlob1 = null;
}
}
}
private static int selectBlobData(final String fileId, final String path) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
BLOB blob = null;
try {
final String query = "SELECT FileName, FileData FROM tblBlobDemo WHERE FileId = " + fileId;
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* Execute the SELECT statement
*/
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Extract the BLOB data to a file on the local file system.
*/
blob = ((OracleResultSet)rs).getBLOB("FileData");
is = blob.getBinaryStream();
final String fileName = rs.getString("FileName");
final String filePath = path + fileName;
os = new FileOutputStream(filePath);
final int bufferSize = blob.getBufferSize();
final byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
else {
returnValue = 1;
}
}
catch(SQLException e) {
returnValue = 2;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 3;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 4;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
blob = null;
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
}
return returnValue;
}
}