【发布时间】: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,你能帮忙吗,我有点笨...
非常感谢
【问题讨论】: