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);
}

最新文章

  1. RecyclerView添加Header的正确方式
  2. WPF -Enum的三种绑定方法
  3. CEPH浅析”系列之三——CEPH的设计思想
  4. Eclipse的各种快捷键
  5. jQuery pgwslideshow 空间相册
  6. CREATE INDEX SELECT COUNT(*)
  7. jquery介绍
  8. 网络流初步——增广路算法(EK)模板
  9. Centos中如何配置Texlive2013中文字体的问题
  10. C#程序员阅读的书籍
  11. VS下使用Google Protobuf完成SOCKET通信
  12. linux oops调试
  13. 第九节、人脸检测之Haar分类器
  14. Vuex速学篇:(2)利用state保存新闻数据
  15. 第三组 通信一班 030 IPv6 RIPng (PT)
  16. jdk环境变量及1.6官方下载地址
  17. Oracle EBS FA 资产编号跳号
  18. Java如何取得当前程序部署的服务器的IP
  19. 【codeforces】【比赛题解】#862 CF Round #435 (Div.2)
  20. 通过WebRTC实现实时视频通信(三)

热门文章

  1. vue-3 this概念
  2. BOM操作、DOM操作、jQuery类库
  3. 四、python解释器、环境变量和多版本共存
  4. 计算机网络12 TCP
  5. JAVA虚拟机-01-JAVA虚拟机家族简介
  6. 有趣的python库-pillow
  7. JZOJ 1083. 【GDOI2006】拯救亚特兰蒂斯
  8. JZOJ 2474. 【GDKOI 2021普及组DAY2】我的世界
  9. python下载图片实现方法
  10. Vulhub 漏洞学习之:Fastjson