打印本文 打印本文 关闭窗口 关闭窗口
在Oracle中存取BLOB对象实现文件的上传和下载
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2799  更新时间:2009/4/22 22:04:22  文章录入:mintao  责任编辑:mintao
以下是BLOB写入数据库的代码:

 

 

 

Connection con = ConnectionFactory.getConnection();

con.setAutoCommit(false);

Statement st = con.createStatement();

st.executeUpdate("insert into BLOBIMG values(103,empty_blob())");

ResultSet rs = st.executeQuery(

          "select contents from  BLOBIMG  where  id=103 for update");

if (rs.next()) {

    //上面代码不变

//这里不能用oracle.sql.BLOB,会报ClassCast 异常

weblogic.jdbc.vendor.oracle.OracleThinBlobblob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) rs.getBlob(1);

    //以后代码也不变

OutputStream outStream = blob.getBinaryOutputStream();

File file = new File("d:\\proxy.txt");

  InputStream fin = new FileInputStream(file);

byte[] b = new byte[blob.getBufferSize()];

        int len = 0;

        while ( (len = fin.read(b)) != -1) {

          outStream.write(b, 0, len);

        }

 

 

 

fin.close();

   outStream.flush();

   outStream.close();

   con.commit();

   con.close();

 

 

 

2.  BLOB出库

从数据库中读出BLOB数据没有上述由于连接池的不同带来的差异,只需要J2SE的标准类java.sql.Blob就可以取得输出流(注意区别java.sql.Blob和oracle.sql.BLOB)。代码如下:

Connection con = ConnectionFactory.getConnection();

con.setAutoCommit(false);

Statement st = con.createStatement();

//这里的SQL语句不再需要”for update”

ResultSet rs = st.executeQuery(

          "select contents from  BLOBIMG  where  id=103 ");

if (rs.next()) {

   java.sql.Blob blob = rs.getBlob(1);

 

 

 

   InputStream ins = blob.getBinaryStream();

 

 

 

    //用文件模拟输出流

File file = new File("d:\\output.txt");

   OutputStream fout = new FileOutputStream(file);

 

 

 

    //下面将BLOB数据写入文件

    byte[] b = new byte[1024];

    int len = 0;

        while ( (len = ins.read(b)) != -1) {

          fout.write(b, 0, len);

        }

  //依次关闭

  fout.close();

上一页  [1] [2] [3] [4]  下一页

打印本文 打印本文 关闭窗口 关闭窗口