JDBC 4.0 (Java 6+) 引入 java.sql.Blob 介面的 createBlob()、setBinaryStream()、getBinaryStream() 等方法,大幅簡化 BLOB 操作,無需再依賴 Oracle 專屬 oracle.sql.BLOB。本文示範標準 JDBC 4.0 寫法。
ojdbc6.jar (MANIFEST.MF 顯示 Specification-Version: 4.0)create sequence seq_blobmodel_id start with 1 increment by 1 nocache; create table blobmodel ( blobid number(10) primary key not null, image blob );
import java.io.*;
import java.sql.*;
import javax.sql.rowset.serial.*;
public class BlobJdbc4Demo {
// 取得連線(略,請自行實作 DataSource 或 DriverManager)
private Connection getConnection() throws SQLException { /* ... */ }
/** 將圖片檔案存入資料庫 */
public int writeBlob(String filePath) throws SQLException, IOException {
String sql = "insert into blobmodel(blobid, image) values(seq_blobmodel_id.nextval, ?)";
int result = 0;
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
// 1. 建立空 Blob 物件(JDBC 4.0)
Blob blob = conn.createBlob();
// 2. 取得輸出流寫入二進位資料
try (OutputStream out = blob.setBinaryStream(1);
FileInputStream fis = new FileInputStream(filePath)) {
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
// 3. 綁定 Blob 並執行
ps.setBlob(1, blob);
result = ps.executeUpdate();
}
return result;
}
/** 從資料庫讀取 Blob 並存檔 */
public void readBlob(long blobId, String outputDir) throws SQLException, IOException {
String sql = "select image from blobmodel where blobid = ?";
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setLong(1, blobId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
Blob blob = rs.getBlob(1);
try (InputStream is = blob.getBinaryStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(outputDir + "/" + System.currentTimeMillis() + ".jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
}
}
}
}
}
}
| JDBC 4.0 標準 API | 舊版 Oracle 專屬 API | 說明 |
|---|---|---|
Connection.createBlob() | new oracle.sql.BLOB(...) | 建立空 Blob |
Blob.setBinaryStream(pos) | blob.getBinaryOutputStream() | 取得寫入流 |
Blob.getBinaryStream() | blob.getBinaryStream() | 取得讀取流 |
PreparedStatement.setBlob(idx, blob) | 相同 | 綁定參數 |
ResultSet.getBlob(idx) | 相同 | 取得結果 |
setBinaryStream(pos, stream, length) 指定長度commit,讀取不需<dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>19.3.0.0</version> </dependency>