【问题标题】:How to query a blob?如何查询 blob?
【发布时间】:2011-06-16 09:15:52
【问题描述】:

我想创建返回一些值的 SQL 查询,其中一个值是 blob

当我将 blob 列放在我的选择中时,它返回 BigDecimal :|

带有参数的普通 JDBC 查询

【问题讨论】:

    标签: java sql jdbc blob


    【解决方案1】:

    正在插入..

    stmt = con.prepareStatement("INSERT INTO TABLE(fileName, "
                + "blobData) VALUES(?, ?)");
            stmt.setString(1, "somefilename");
            stmt.setObject(2, data);//data is byte[]
            stmt.executeUpdate();
    

    正在选择..

    ResultSet rs;
    
        stmt = con.prepareStatement("SELECT blobData "
            + "FROM BlobTest " + "WHERE fileName = ?");
    
        stmt.setString(1, "somevalue");
        rs = stmt.executeQuery();
        if (!rs.next()) {
          System.out.println("No such file stored.");
        } else {
          Blob b = rs.getBlob(1);
          BufferedOutputStream os;
    

    【讨论】:

    • 实际上 setBytes()(而不是 setObject())可能更便携。但这在很大程度上取决于 JDBC 驱动程序
    【解决方案2】:

    尝试从 ResultSet 中调用 getBytes() 方法:

    stmt = dbConn.prepareStatement("SELECT ...");
    ResultSet rs = stmt.executeQuery();
    byte[] blob = rs.getBytes(1);
    

    这应该将您的 blob 对象作为字节数组返回。

    【讨论】:

      【解决方案3】:

      查看Materializing Blob Data 上的 javadocs 部分。

      你需要在blob列上调用getBlob,然后读取二进制流。

          Blob blob = rs.getBlob("BLOB_COLUMN_NAME");        
          InputStream blobStream = blob.getBinaryStream();
      
          //e.g. save blob to a file
          FileOutputStream out = new FileOutputStream("file.txt");
          byte[] buffer = new byte[1024];
          int n = 0;  
          while( (n = blobStream.read(buffer)) != -1 ) {
              out.write(buffer, 0, n);
          }
          out.flush();
          out.close();
          blobStream.close();
      

      【讨论】:

        猜你喜欢
        • 2012-11-26
        • 2016-12-07
        • 2015-09-14
        • 1970-01-01
        • 2022-11-15
        • 2016-02-08
        • 2021-12-31
        • 2023-03-07
        • 2012-12-30
        相关资源
        最近更新 更多