案例1-导出Blob字段图像

需求:

有一张单表存储着图片(图片使用Blob字段)以及图片的相关信息,需求是从数据库中将这些Blob字段内容保存为图片文件,文件名为图片的相关信息。

环境

数据库:Oracle本地:Windows工具:Hutool-db模块

编码

数据库配置:src/main/resources/config/db.setting

  1. # -------------------------------------------------------------
  2. # ----- Setting File with UTF8-----
  3. # ----- 数据库配置文件 -----
  4. # -------------------------------------------------------------
  5. #JDBC url,必须
  6. url = jdbc:oracle:thin:@192.168.1.1:1521/orcl
  7. #用户名,必须
  8. user = test
  9. #密码,必须,如果密码为空,请填写 pass =
  10. pass = test

代码:PicTransfer.java

  1. public class PicTransfer {
  2. private static SqlRunner runner = SqlRunner.create();
  3. private static String destDir = "f:/pic";
  4. public static void main(String[] args) throws SQLException {
  5. runner.find(
  6. CollUtil.newArrayList("NAME", "TYPE", "GROUP", "PIC"),
  7. Entity.create("PIC_INFO").set("TYPE", 1),
  8. new RsHandler<String>(){
  9. @Override
  10. public String handle(ResultSet rs) throws SQLException {
  11. while(rs.next()){
  12. save(rs);
  13. }
  14. return null;
  15. }
  16. }
  17. );
  18. }
  19. private static void save(ResultSet rs) throws SQLException{
  20. String path = StrUtil.format("{}/{}-{}.jpg", destDir, rs.getString("NAME"), rs.getString("GROUP"));
  21. FileUtil.writeFromStream(rs.getBlob("PIC").getBinaryStream(), path);
  22. }
  23. }