当前位置: 首页 > news >正文

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();}}
}
http://www.dtcms.com/a/556791.html

相关文章:

  • 目标跟踪 deepsort
  • 网站建设前的分析第一小节内容好看网页设计
  • SAP PP生产版本批量维护功能分享
  • 【Linux】当遇到不是root用户,无法进入root用户,却仍需要使用sudo命令时
  • Python 生成书法字体(以瘦金体为例)
  • Advanced Science 国防科大开发1.8克人仿生眼球,实现微型化与功能集成度兼具!
  • 数据结构05:顺序表经典算法
  • 静态网站开发课程深圳东门网红打卡地
  • Ubuntu 24.04下编译支持ROCm加速的llama.cpp
  • 如何在DCU上面编译llama.cpp
  • 具身导航轨迹规划与主动想象融合!DreamNav:基于轨迹想象的零样本视觉语言导航框架
  • AWS + SEO:让网站从服务器层面赢在搜索引擎起跑线
  • 深度学习(9)导数与计算图
  • 好看的网站建设公司中企动力网站建设公司
  • JavaSe—泛型
  • ssm面试题梳理
  • 基于MATLAB的二维图像三维重建算法比较研究
  • SVG 参考手册
  • 微软Copilot+企业版亮相:GPT-5赋能,效率激增47%,多模态操控金融级安全
  • 我在高职教STM32(新08)——初识LCD1602
  • 购买qq空间访客的网站一般app开发费用多少
  • 有没有个人做网站的长沙装修公司排行榜
  • 【新能源汽车的电机控制器控制电机过程中,谐波、纹波、载频、谐振、NVH等几个关键词之间有什么相互、因果关系】
  • 技术准备十二:FastDFS
  • Linux(MAIL服务)
  • GetFieldID函数介绍
  • 二分查找为什么总是写错
  • PPO算法:从深度学习视角入门强化学习
  • 《数据结构风云》递归算法:二叉树遍历的精髓实现
  • 广州网站建设学习郑州官网seo推广