Writing to a new Blob in Java

て烟熏妆下的殇ゞ 提交于 2019-12-13 09:54:58

问题


I want to be able to create a new Blob object and then write to it. Originally, my general plan for this was as follows:

Create a new blob (null, because there's no Blob constructor) Create a new OutputStream and set it to blob.setBinaryStream(0) Write to the output stream.

However, I get a NullPointerException when I try to execute this code. Is there a different way I should be going about this? Any help would be appreciated.

Thanks!

~B


回答1:


java.sql.Blob is an interface and not a class, thus no constructor can exist. But you can instantiate the implementing class SerialBlob which allows you to construct a blob from a byte array.




回答2:


Create a new blob (null, because there's no Blob constructor) Create a new OutputStream and set it to blob.setBinaryStream(0) Write to the output stream.

However, I get a NullPointerException when I try to execute this code.

Yes, that's not a surprise - you will get a NullPointerException when you try to call a method on a variable that is null (as is your blob variable).

You should call setBinaryStream on your PreparedStatement object instead. Suppose that you have the data in a byte[], then you could do something like this:

byte[] data = ...;

PreparedStatement ps = connection.prepareStatement(...);

ByteArrayInputStream stream = new ByteArrayInputStream(data);

ps.setBinaryStream(1, stream);

ps.executeUpdate();



回答3:


If you want to use the Blob in a CallableStatement or a PreparedStatement, you don't actually need to create a Blob object itself. The setBlob methods come in flavors that take an InputStream in place of a Blob object. You could, for instance, write to a ByteArrayOutputStream, retrieve the byte array, and then wrap that in a ByteArrayInputStream. Or you could use piped streams.



来源:https://stackoverflow.com/questions/6376431/writing-to-a-new-blob-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!