-
Java mysql blob 数据读写操作
package com.lw.database; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * CREATE: CREATE TABLE IDCard ( id char(18),pic BLOB); * @author fhadmin * from www.fhadmin.cn */ public class LOBTest { protected static final String DEFAULT_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8"; protected static final String DRIVER_NAME = "com.mysql.jdbc.Driver"; private Connection connection = null; public LOBTest() throws ClassNotFoundException, SQLException { Class.forName(DRIVER_NAME); connection = DriverManager.getConnection(DEFAULT_URL, "user", "password"); } public void insert(String id,String path) throws SQLException, IOException { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO IDCard VALUES (?,?)"); preparedStatement.setString(1, id); FileInputStream fileInputStream = new FileInputStream(path); preparedStatement.setBlob(2, fileInputStream,fileInputStream.available()); preparedStatement.execute(); } public void get(String id) throws SQLException, IOException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT pic FROM IDCard WHERE id = ?"); preparedStatement.setString(1, id); ResultSet results = preparedStatement.executeQuery(); while(results.next()) { FileOutputStream outputStream = new FileOutputStream("/Users/liuwei/temp.png"); InputStream inputStream = results.getBinaryStream(1); int num = -1; while((num=inputStream.read())!=-1) { outputStream.write(num); } outputStream.flush(); inputStream.close(); outputStream.close(); } } public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException { LOBTest test = new LOBTest(); test.insert("78907656784323", "/Users/liuwei/Documents/bt_next_nor.png"); test.get("78907656784323"); } }
注意:
MySQL的四种BLOB类型
类型 大小(单位:字节)
TinyBlob 最大 255B
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G
插入图像的时候,注意下图像大小,图像超过该类型所能容纳的最大字节的时候,会报错
出处:
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
数据库审计与智能监控:从日志分析到异
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比