首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JDBC 實現文件與圖片存入數據庫 (BLOB/CLOB)

     編輯:Java 相關知識

數據庫存儲二進制文件使用 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 壓力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved