Oracle数据库保存、下载图片

来源:互联网 发布:c语言倒九九乘法表 编辑:程序博客网 时间:2024/05/29 07:24

存储图片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, 0, data.length);         op.close()

获取conn省略。

0 0