Oracle的Blob字段比較非凡,他比long字段的性能要好很多,可以用來保存例如圖片之類的二進制數據。
寫入Blob字段和寫入其它類型字段的方式非常不同,因為Blob自身有一個cursor,你必須使用cursor對blob進行操作,因而你在寫入Blob之前,必須獲得cursor才能進行寫入,那麼如何獲得Blob的cursor呢?
這需要你先插入一個empty的blob,這將創建一個blob的cursor,然後你再把這個empty的blob的cursor用select查詢出來,這樣通過兩步操作,你就獲得了blob的cursor,可以真正的寫入blob數據了。
看下面的JDBC的demo,把oraclejdbc.jar這個二進制文件寫入數據庫表Javatest的content字段(這是一個blob型字段)
import java.sql.*;
import java.io.*;
import oracle.sql.*;
public class WriteBlob {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","fankai","fankai");
conn.setAutoCommit(false);
BLOB blob = null;
PreparedStatement pstmt = conn.prepareStatement("insert into javatest(name,content) values(?,empty_blob())");
pstmt.setString(1,"fankai");
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement("select content from javatest where name= ? for update");
pstmt.setString(1,"fankai");
ResultSet rset = pstmt.executeQuery();
if (rset.next()) blob = (BLOB) rset.getBlob(1);
String fileName = "oraclejdbc.jar";
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
System.out.println("file size = " + fin.available());
pstmt = conn.prepareStatement("update javatest set content=? where name=?");
OutputStream out = blob.getBinaryOutputStream();
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
fin.read(data);
out.write(data);
/*
byte[] data = new byte[blob.getBufferSize()]; 另一種實現方法,節省內存
while ((count = fin.read(data)) != -1) {
total += count;
out.write(data, 0, count);
}
*/
fin.close();
out.close();