Writing to a new Blob in Java

2019-09-25 06:50发布

问题:

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.