BLOB 数据的插入与读取详解
BLOB 数据的插入与读取详解
在数据库操作中,BLOB(Binary Large Object)类型用于存储大型二进制数据,如图片、音频、视频、PDF 文件等。下面我将详细说明如何使用 JDBC 和 PreparedStatement
处理 BLOB 数据。
📦 BLOB 数据类型概述
数据库 | BLOB 类型 | 最大大小 |
---|---|---|
MySQL | BLOB , LONGBLOB | 4GB (LONGBLOB) |
Oracle | BLOB | 4GB |
SQL Server | VARBINARY(MAX) | 2GB |
PostgreSQL | BYTEA , OID (大对象) | 1GB (BYTEA) |
🧩 BLOB 数据插入流程
1. 创建数据库表
CREATE TABLE documents (id INT PRIMARY KEY AUTO_INCREMENT,file_name VARCHAR(255) NOT NULL,content LONGBLOB, -- MySQLmime_type VARCHAR(100) -- 存储文件类型
);
2. Java 插入 BLOB 数据
public void saveDocument(String fileName, InputStream inputStream, String mimeType) {String sql = "INSERT INTO documents (file_name, content, mime_type) VALUES (?, ?, ?)";try (Connection conn = dataSource.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {// 设置文件名和MIME类型pstmt.setString(1, fileName);pstmt.setString(3, mimeType);// 设置BLOB参数if (inputStream != null) {pstmt.setBinaryStream(2, inputStream);} else {pstmt.setNull(2, Types.BLOB);}int affectedRows = pstmt.executeUpdate();if (affectedRows == 0) {throw new SQLException("Insert failed, no rows affected.");}} catch (SQLException e) {throw new DataAccessException("Failed to save document", e);}
}
3. 使用示例
// 从文件系统读取文件
File file = new File("path/to/document.pdf");
try (FileInputStream fis = new FileInputStream(file)) {documentDao.saveDocument(file.getName(), fis, "application/pdf");
}
📥 BLOB 数据读取流程
1. Java 读取 BLOB 数据
public Document getDocumentById(int id) {String sql = "SELECT file_name, content, mime_type FROM documents WHERE id = ?";Document document = new Document();try (Connection conn = dataSource.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setInt(1, id);try (ResultSet rs = pstmt.executeQuery()) {if (rs.next()) {document.setId(id);document.setFileName(rs.getString("file_name"));document.setMimeType