zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    如何得到需要下载文件的链接(路径)?
    Python之内存泄漏和内存溢出
    IO多路复用
    python-socket和进程线程协程(代码展示)
    Xshell(远程)连接不上linux服务器(防火墙介绍)
    Shell--变量
    Python读写配置文件模块--Configobj
    python文件处理之fileinput
    python之commands和subprocess入门介绍(可执行shell命令的模块)
    linux下 > /dev/null 2 > &1 的意思和如何在后台启动进程
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/8885388.html
Copyright © 2011-2022 走看看