mysql保存二进制数据
学习链接
mysql数据类型
文章目录
- 学习链接
- 建表
- BinaryDataStorage
- BinaryDataExample
建表
DROP TABLE IF EXISTS binary_data;
CREATE TABLE binary_data (id INT PRIMARY KEY AUTO_INCREMENT,file_name VARCHAR(255) NOT NULL,file_data LONGBLOB,created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);select * from binary_data;
BinaryDataStorage
import java.io.*;
import java.sql.*;
import java.util.Properties;public class BinaryDataStorage {private Connection getConnection() throws SQLException {String url = "jdbc:mysql://localhost:3306/test";Properties props = new Properties();props.setProperty("user", "root");props.setProperty("password", "root");props.setProperty("useSSL", "false");props.setProperty("serverTimezone", "GMT+8");return DriverManager.getConnection(url, props);}// 方法1: 使用 byte[] 保存二进制数据public void saveBinaryDataAsBytes(String fileName, byte[] data) throws SQLException {String sql = "INSERT INTO binary_data (file_name, file_data) VALUES (?, ?)";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setString(1, fileName);pstmt.setBytes(2, data); // 直接设置byte数组int affectedRows = pstmt.executeUpdate();System.out.println("保存成功,影响行数: " + affectedRows);}}// 方法2: 使用 InputStream 保存二进制数据public void saveBinaryDataAsStream(String fileName, InputStream inputStream) throws SQLException, IOException {String sql = "INSERT INTO binary_data (file_name, file_data) VALUES (?, ?)";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setString(1, fileName);pstmt.setBinaryStream(2, inputStream); // 设置输入流int affectedRows = pstmt.executeUpdate();System.out.println("保存成功,影响行数: " + affectedRows);}}// 方法3: 使用 Blob 保存二进制数据public void saveBinaryDataAsBlob(String fileName, byte[] data) throws SQLException {String sql = "INSERT INTO binary_data (file_name, file_data) VALUES (?, ?)";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setString(1, fileName);Blob blob = conn.createBlob();blob.setBytes(1, data);pstmt.setBlob(2, blob); // 设置Blob对象int affectedRows = pstmt.executeUpdate();System.out.println("保存成功,影响行数: " + affectedRows);}}// -------------------------------------------------// 方法1: 查询并返回 byte[]public byte[] retrieveBinaryDataAsBytes(int id) throws SQLException {String sql = "SELECT file_data FROM binary_data WHERE id = ?";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setInt(1, id);ResultSet rs = pstmt.executeQuery();if (rs.next()) {return rs.getBytes("file_data"); // 直接获取byte数组}}return null;}// 方法2: 查询并返回 InputStreampublic InputStream retrieveBinaryDataAsStream(int id) throws SQLException {String sql = "SELECT file_data FROM binary_data WHERE id = ?";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setInt(1, id);ResultSet rs = pstmt.executeQuery();if (rs.next()) {return rs.getBinaryStream("file_data"); // 获取二进制流}}return null;}// 方法3: 查询并返回 Blobpublic Blob retrieveBinaryDataAsBlob(int id) throws SQLException {String sql = "SELECT file_data FROM binary_data WHERE id = ?";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setInt(1, id);ResultSet rs = pstmt.executeQuery();if (rs.next()) {return rs.getBlob("file_data"); // 获取Blob对象}}return null;}// 方法4: 分块读取大文件(适合大文件处理)public void retrieveLargeBinaryData(int id, OutputStream outputStream) throws SQLException, IOException {String sql = "SELECT file_data FROM binary_data WHERE id = ?";try (Connection conn = getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) {pstmt.setInt(1, id);ResultSet rs = pstmt.executeQuery();if (rs.next()) {try (InputStream inputStream = rs.getBinaryStream("file_data")) {byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}}}}
}
BinaryDataExample
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;public class BinaryDataExample {public static void main(String[] args) {BinaryDataStorage storage = new BinaryDataStorage();try {// 示例1: 保存文本数据作为二进制String textData = "这是一个示例文本数据";byte[] textBytes = textData.getBytes("UTF-8");storage.saveBinaryDataAsBytes("example.txt", textBytes);// 示例2: 保存图片文件File imageFile = new File(System.getProperty("user.dir") + "\\logo.jpg");try (FileInputStream fis = new FileInputStream(imageFile)) {storage.saveBinaryDataAsStream("example.jpg", fis);}// ----------------查询// 示例1: 查询数据作为byte[]byte[] retrievedBytes = storage.retrieveBinaryDataAsBytes(1);if (retrievedBytes != null) {String retrievedText = new String(retrievedBytes, "UTF-8");System.out.println("检索到的文本: " + retrievedText);}// 示例2: 查询数据作为InputStream并保存到文件try (InputStream is = storage.retrieveBinaryDataAsStream(2);FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir") + "\\retrieved_image.jpg")) {byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = is.read(buffer)) != -1) {fos.write(buffer, 0, bytesRead);}System.out.println("文件保存成功");}// 示例3: 使用Blob处理Blob blob = storage.retrieveBinaryDataAsBlob(1);if (blob != null) {byte[] blobData = blob.getBytes(1, (int) blob.length());System.out.println("Blob数据长度: " + blobData.length);blob.free(); // 释放资源}// 示例4: 检索大文件并保存到文件storage.retrieveLargeBinaryData(2, new FileOutputStream(System.getProperty("user.dir") + "\\retrieved_large_file.jpg"));} catch (Exception e) {e.printStackTrace();}}
}
