用 Java 写入新的 Blob
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6376431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing to a new Blob in Java
提问by Benjadette
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:
我希望能够创建一个新的 Blob 对象,然后写入它。本来,我对此的总体计划如下:
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.
创建一个新的 blob(null,因为没有 Blob 构造函数) 创建一个新的 OutputStream 并将其设置为 blob.setBinaryStream(0) 写入输出流。
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.
但是,当我尝试执行此代码时,出现 NullPointerException。我应该采取不同的方式来解决这个问题吗?任何帮助,将不胜感激。
Thanks!
谢谢!
~B
~B
回答by Howard
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.
java.sql.Blob
是接口而不是类,因此不能存在构造函数。但是您可以实例化实现类SerialBlob
,该类允许您从字节数组构造一个 blob。
回答by Jesper
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.
创建一个新的 blob(null,因为没有 Blob 构造函数) 创建一个新的 OutputStream 并将其设置为 blob.setBinaryStream(0) 写入输出流。
但是,当我尝试执行此代码时,出现 NullPointerException。
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).
是的,这并不奇怪 -NullPointerException
当您尝试调用一个变量的方法时,您会得到一个null
(就像您的blob
变量一样)。
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:
你应该调用setBinaryStream
你的PreparedStatement
对象。假设您在 a 中有数据byte[]
,那么您可以执行以下操作:
byte[] data = ...;
PreparedStatement ps = connection.prepareStatement(...);
ByteArrayInputStream stream = new ByteArrayInputStream(data);
ps.setBinaryStream(1, stream);
ps.executeUpdate();
回答by Ted Hopp
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.
如果您想在 CallableStatement 或 PreparedStatement 中使用 Blob,您实际上不需要创建 Blob 对象本身。这些setBlob
方法具有使用 InputStream 代替 Blob 对象的风格。例如,您可以写入 ByteArrayOutputStream,检索字节数组,然后将其包装在 ByteArrayInputStream 中。或者您可以使用管道流。