• BLOB 操作


    对于数据库是BLOB类型存储数据。

    BLOB数据插入:

    Oracle提供的标准方式: 先插入一个空BLOB对象,然后Update这个空对象。

    首先使用empty_blob()函数插入一个空BLOB对象。

    然后重新查询BLOB,使用for update锁字段,注意关闭连接和回滚或提交。

    ResultSet 获取 BLOB对象。

    BLOB.setByte(byte);  //这个无效,数据存不进去,不能用

    或者 OutputStream os = blob.setBinaryStream(0); // 0设置起始位置

    blob.getOutputStream();  //已经deprecated

    ResultSet 和 Statement  会在连接关闭时自动关闭,因此无需自己关闭。

        /**
         * 保存附件Blob
         * @param attachId
         * @throws SQLException 
         */
        private void setAttachBlob(long attachId, String fileData) throws SQLException {
            logger.debug(">>>setAttachBlob(long attachId)");
            StringBuilder sql = new StringBuilder();
            sql.append(" select file_data fileData from test_attach where attach_id=" + attachId + "  for update");
            Connection connection = null;
            try {
                byte[] byteStream = Base64.decodeBase64(fileData.getBytes("UTF-8"));
                connection = super.getDbHelper().getConnection();
                connection.setAutoCommit(false);

    ResultSet rs = connection.prepareStatement(sql.toString())
    .executeQuery();
    if (rs.next()) {
    BLOB blob = (BLOB) rs.getBlob("fileBody");
    OutputStream os = blob.setBinaryStream(0);
    ByteArrayInputStream is = new ByteArrayInputStream(byteStream);
    byte[] byteData = new byte[512];
    int len = 0;
    try {
    while((len = is.read(byteData, 0 , 512)) != -1) {
    os.write(byteData, 0, len);
    }
    os.flush();
    } catch (IOException e) {
    logger.error("file read write error.", e);
    } finally {
    if(is != null) {
    is.close();
    }
    if(os != null) {
    os.close();
    }
    }
    }

    
                connection.commit();
            } catch (UnsupportedEncodingException e) {
                logger.error("decode error  file get byte...", e);
                e.printStackTrace();
            } catch (DbException e) {
                connection.rollback();
                logger.error("blob save error...", e);
            }finally {
                // 关闭连接
                if(connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            logger.debug("<<<setAttachBlob(long attachId)");
        }

    获取BLOB比较简单:

    ResultSet rs = st.executeQuery( "select file_data from  test_attach  where  attach_id=103 ");
    
    if (rs.next()) {
    
       java.sql.Blob blob = rs.getBlob("file_data ");
    
       InputStream ins = blob.getBinaryStream();
  • 相关阅读:
    BoundsChecker使用
    完成端口(Completion Port)详解
    VC内存泄露检查工具:VisualLeakDetector
    AcceptEx函数与完成端口的结合使用例子
    IOCP之accept、AcceptEx、WSAAccept的区别
    Visual C++ 6.0安装
    eclipse中在线安装FindBugs
    几种开源SIP协议栈对比
    全情投入是做好工作的基础——Leo鉴书39
    CheckStyle检查项目分布图
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/8885388.html
Copyright © 2020-2023  润新知