數據庫存儲二進制文件使用 BLOB (Binary Large Object),大文本使用 CLOB。JDBC 流程:PreparedStatement 設置二進制流或字符流 → 執行插入/更新 → 讀取時獲取 Blob/Clob 對象 → 通過 getBinaryStream/getCharacterStream 讀取。
// 存入圖片
String sql = "INSERT INTO files(name, content) VALUES(?, ?)";
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
InputStream is = new FileInputStream("photo.jpg")) {
ps.setString(1, "photo.jpg");
ps.setBinaryStream(2, is);
ps.executeUpdate();
}
// 讀取圖片
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT content FROM files WHERE id=?")) {
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("content");
try (InputStream is = blob.getBinaryStream();
OutputStream os = new FileOutputStream("out.jpg")) {
is.transferTo(os); // Java 9+
}
}
}
大文件建議分塊讀寫避免 OOM。MySQL 需設置 max_allowed_packet,Oracle 需先 empty_blob() 再寫入。現代架構推薦對象存儲 (S3/MinIO) + 數據庫存 URL,減輕 DB 壓力。