postgresql数据库插入和读取图片
2024-09-18 18:31:55
postgresql插入和读取图片
postgresql存储图片需要二进制类型bytea,创建一张测试表:
postgres=# create table test_image(img bytea);
CREATE TABLE
使用jdbc插入1.jpg
try {
connection = JDBCUtil.getConnection();
connection.setAutoCommit(false);
String sql = "INSERT INTO test_image(img) VALUES(?)";
preparedStatement = connection.prepareStatement(sql);
InputStream inputStream = new FileInputStream(img_name);
preparedStatement.setBinaryStream(1,inputStream);
preparedStatement.executeUpdate();
connection.commit();
} catch (SQLException | FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil.release(connection);
}
查看字段长度
postgres=# select length(img) from test_image;
length
--------
50726
(1 row)
读取图片
try {
connection = JDBCUtil.getConnection();
String sql = "SELECT img from test_image";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
InputStream in = resultSet.getBinaryStream(1);
byte[] buffer = new byte[1024*1024];
OutputStream out = new FileOutputStream("new_1.jpg");
for (int i; (i = in.read(buffer)) > 0;)
{
out.write(buffer, 0, i);
out.flush();
}
out.close();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.release(connection);
}
最新文章
- RecyclerView添加Header的正确方式
- WPF -Enum的三种绑定方法
- CEPH浅析”系列之三——CEPH的设计思想
- Eclipse的各种快捷键
- jQuery pgwslideshow 空间相册
- CREATE INDEX SELECT COUNT(*)
- jquery介绍
- 网络流初步——增广路算法(EK)模板
- Centos中如何配置Texlive2013中文字体的问题
- C#程序员阅读的书籍
- VS下使用Google Protobuf完成SOCKET通信
- linux oops调试
- 第九节、人脸检测之Haar分类器
- Vuex速学篇:(2)利用state保存新闻数据
- 第三组 通信一班 030 IPv6 RIPng (PT)
- jdk环境变量及1.6官方下载地址
- Oracle EBS FA 资产编号跳号
- Java如何取得当前程序部署的服务器的IP
- 【codeforces】【比赛题解】#862 CF Round #435 (Div.2)
- 通过WebRTC实现实时视频通信(三)