【问题标题】:How to insert a 300MB blob in jdbc mysql without OutOfMemoryError?如何在没有 OutOfMemoryError 的情况下在 jdbc mysql 中插入 300MB blob?
【发布时间】:2015-06-28 11:51:05
【问题描述】:

我想在 mysql 中插入一个 300MB 的 blob,但我似乎没能做到。我总是遇到 OutOfMemoryError。

我已经设置了 max_allowed_packet = 500M在我的.cn。

这是我的代码:

@Test
    public void testWriteBlobWithJdbc() throws IOException {
        System.out.println("Memory is " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + " MB");
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost/lazy_lob?user=root&password=itismeDA02071986");
            PreparedStatement preparedStatement = connection.prepareStatement("insert into addresses(description) values(?);");
            Blob blob = connection.createBlob();
            BufferedOutputStream bos = new BufferedOutputStream(blob.setBinaryStream(1));
            bos.write(get300MBData());
            bos.flush();
            bos.close();
            preparedStatement.setBlob(1, blob);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {

            }
        }
    }

这是我得到的:

Memory is 910 MB

java.lang.OutOfMemoryError: Java heap space
    at com.mysql.jdbc.Blob.getBytes(Blob.java:132)
    at com.mysql.jdbc.PreparedStatement.setBlob(PreparedStatement.java:2934)
    at cgad.learning.hibernate.TestLazyLoadLob.testWriteBlobWithJdbc(TestLazyLoadLob.java:64)

所以基本上我有 910MB 的 RAM,但我不能插入 300MB 的 blob? 另外,我认为这应该将 blob 流式传输到 db,但它似乎被加载到内存中并可能导致一些问题?

如果你用过 blob,你能帮忙吗,我有点笨...

非常感谢

【问题讨论】:

    标签: jdbc blob


    【解决方案1】:

    不要一次将整个 300MB 放入一个巨大的字节数组中。一次将其写入 Blob 流。

    Blob 类会流式传输 Blob。没有流式传输的实体是您。

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 2011-06-28
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      相关资源
      最近更新 更多