Oracle数据库保存、下载图片

前端之家收集整理的这篇文章主要介绍了Oracle数据库保存、下载图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

存储图片class:
test表结构( id name image)

public class Test{
    PreparedStatement pst = null;
    Result rs = null;
    Connection conn = ConnectionManager.getConnection();
    String sql = "insert into test(id,name,image) values(?,?,?)";
    try {
          pst = conn.prepareStatement(sql);
          pst.setInt(0,1);
          pst.setString(1,"testData");
          //事先插入空对象empty_blob()  
          pst.setBlob(2,BLOB.empty_lob()); 
          pst.executeUpdate();

          OutputStream os = null;
          // for update 锁定数据行进行更新
          String q_sql = "select image from test_img where id = ? for update"; 
          pst = conn.prepareStatement(q_sql);
          pst.setInt(1,1);
          rs = pst.executeQuery();
          if (rs.next()) {
              oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("image");
              os = blob.getBinaryOutputStream();
              InputStream is = new FileInputStream("C:\\image.jpg");
              int i = 0;
              while ((i = is.read()) != -1) {
                  os.write(i);
              }
          }
          is.close();
          os.flush();
          os.close();
          ConnectionManager.closeAll(rs,pst,conn); // 关闭资源

      } catch (sqlException e) {
            e.printStackTrace();
      } catch (FileNotFoundException e) {
            e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
    }
}

根据id获取图片byte数据

public class Query{
 public byte[] GetImgByteById(Int id,Connection conn){   
    byte[] data = null;  
    try {  
            String sql = "select image from test where id = ?";
            PreparedStatement pst = null;  
            pst = conn.prepareStatement(sql);
            pst.setInt(0,id);
            rs = pst.executeQuery();

            StringBuffer myStringBuffer = new StringBuffer();  
            if (rs.next()) {  
                java.sql.Blob blob = rs.getBlob("image");  
                InputStream in = blob.getBinaryStream();  
                try {  
                    long nLen = blob.length();  
                    int nSize = (int) nLen;  
                    data = new byte[nSize];  
                    in.read(data);  
                    in.close();  
                } catch (IOException e) {  
                    System.out.println("获取图片数据失败,原因:" + e.getMessage());  
                }  

            }  
            System.out.println(myStringBuffer.toString());  
            conn.commit();  
            conn.close();  
        } catch (sqlException ex) {  
            System.out.println(ex.getMessage());  
        }  
        return data;  
    }
}

处理byte数据:

//获取图片的byte数据  
        id = 1;
        data = Query.GetImgByteById(id); 
        ServletOutputStream op = response.getOutputStream();         
       op.write(data,data.length); 
       op.close()

获取conn省略。

原文链接:https://www.f2er.com/oracle/209621.html

猜你在找的Oracle相关文章