zoukankan      html  css  js  c++  java
  • JDBC(四)—— Blob类型操作

    Blob类型的数据的操作

    Blob类型:2进制大数据

    四种Blob类型:

    1. TinyBlob:最大255(字节)

    2. Blob:最大65K

    3. MediumBlob:最大16M

    4. LongBlob:最大4G

    根据数据大小选择相应的大小

    向数据表中插入Blob类型的数据

    //向数据表插入Blob类型字段
    @Test
    public void testInsert() throws Exception {
       Connection conn = JdbcUtils.getConnection();
       String sql = "insert into blobtest (username,password,photo) values (?,?,?)";
       PreparedStatement ps = conn.prepareStatement(sql);
       ps.setObject(1,"why");
       ps.setObject(2,"123");
       FileInputStream is = new FileInputStream(new File("D:\photo\anglebaby.jpg"));
       ps.setBlob(3,is);
       ps.execute();
       JdbcUtils.closeResource(conn,ps);
    }

    查询数据表中的Blob类型的数据

    //查询数据
    @Test
    public void testQuery() {
       InputStream is = null;
       FileOutputStream fos = null;
       Connection conn = null;
       PreparedStatement ps = null;
       ResultSet rs = null;
       try {
           conn = JdbcUtils.getConnection();
           String sql = "select photo from blobtest where id = ?";
           ps = conn.prepareStatement(sql);
           ps.setObject(1,1);
           rs = ps.executeQuery();
           if (rs.next()){
               //方式一:
    //           Blob photo = rs.getBlob(1);
               //方式二:
               Blob photo = rs.getBlob("photo");
               //下载以文件的方式保存至本低
               is = photo.getBinaryStream();
               fos = new FileOutputStream("D:\word\anglebaby.jpg");
               byte[] buffer = new byte[1024];
               int len;
               while ((len = is.read(buffer))!=-1){
                   fos.write(buffer,0,len);
              }
          }
      } catch (Exception e) {
           e.printStackTrace();
      }finally {
           JdbcUtils.closeResource(conn,ps,rs);
           try {
               is.close();
               fos.close();
          } catch (IOException e) {
               e.printStackTrace();
          }
      }

    }

     

  • 相关阅读:
    使用 Markdown Flow 画流程图
    两串锂电池的电池匹配
    笔记: CC2540 和 CC2541 的区别
    Elasticsearch 5.x 关于term query和match query的认识
    es 批量导入文件
    mac 下搭建Elasticsearch 5.4.3分布式集群
    Elastic Search 5.4.3 java api 入门
    solr java demo 基础入门
    创建索引并进行查询
    RabbitMq 之简单队列
  • 原文地址:https://www.cnblogs.com/whystudyjava/p/14135396.html
Copyright © 2011-2022 走看看