【问题标题】:convert Blob into a bytea in java在java中将Blob转换为bytea
【发布时间】:2012-08-24 21:48:03
【问题描述】:

我在 postgresql 数据库中工作,我需要仅使用 java 代码将 MYSQL Blob 数据类型转换为 PostgreSQL bytea 有没有办法做到这一点?

【问题讨论】:

    标签: java postgresql jdbc postgresql-9.1


    【解决方案1】:
    //(assuming you have a ResultSet named RS)
    PreparedStatement psMySql = connMySql.prepareStatement("select myBlob from myTable where ...");
    Blob blob = rs.getBlob("myBlob");
    
    int blobLength = (int) blob.length();  
    byte[] blobAsBytes = blob.getBytes(1, blobLength);
    
    PreparedStatement psPostresql = connPostgresql.prepareStatement("INSERT INTO myNewTable VALUES (?, ?)");
    psPostresql.setString(1, myId);
    psPostresql.setBytes(2, blobAsBytes);
    psPostresql.executeUpdate();
    
    //release the blob and free up memory.
    blob.free();
    

    【讨论】:

    • 使用上面的代码我已经将 Blob 转换为 java 中的 bytea,但现在我无法从 postgresql 获取 bytea,我尝试按照此链接进行检索 postgresql.org/docs/7.2/static/jdbc-binary-data.html
    • 它将记录,ppt,excel,图像
    • 它将存储文档,当我尝试检索时,我在文件中得到像 314530413142313141 这样的数字
    • @Stahish :因此,如果您尝试将其作为文件检索,如果您打开该文件,它就不起作用?
    • 当我尝试打开时检索文件后,该文件只包含像 314530413142313141 这样的数字
    【解决方案2】:

    据我所知,两者都支持 JDBC 驱动程序。并且 JDBC 具有处理 BLOB 的标准方法。我一直在 DB2 中这样做。

    所以:

    • 连接到 MySQL
    • 进行选择。假设 blob 列是 FIELD_BLOB
    • rs.getBytes("FIELD_BLOB")
    • 连接到 Postgres
    • 做一个 PreparedStatement
    • 在此 preparestatement 上调用 setBytes,传入您从 MySQL 获得的字节

    如果 getBytes、setBytes 不起作用,请尝试使用输入和输出流。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 2021-05-25
      • 2016-01-01
      • 2018-03-02
      • 2023-02-17
      • 2013-06-28
      • 2015-08-04
      相关资源
      最近更新 更多