java getBytes vs getBinaryStream vs getBlob 用于从 BLOB 列中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/760781/
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
getBytes vs getBinaryStream vs getBlob for getting data out of a BLOB column
提问by Kapsh
There are 3 different ways to get data out of a Blob column: getBytes getBinaryStream getBlob
有 3 种不同的方法可以从 Blob 列中获取数据: getBytes getBinaryStream getBlob
Also, the Blob object returned by getBlob also has a getBytes and getBinaryStream on it.
此外,getBlob 返回的 Blob 对象上也有 getBytes 和 getBinaryStream。
Are there any particular reasons (performance, memory, database specific problems) that I should pick one over the other?
是否有任何特殊原因(性能、内存、数据库特定问题)我应该选择一个?
The Blob object also has a free() call that has been introduced since JDBC 4.0. Does that make a difference?
Blob 对象还有一个从 JDBC 4.0 开始引入的 free() 调用。这有什么区别吗?
采纳答案by skaffman
If you're going to be pulling a lot of data (i.e. enough data to cause memory problems), then getBinaryStream will give you most flexibility to process and discard the data as you read it in.
如果您要提取大量数据(即足够的数据导致内存问题),那么 getBinaryStream 将为您提供最大的灵活性来处理和丢弃您读入的数据。
On the other hand, this could be quite slow, depending on your JDBC driver, since each read from the stream could entail a lot of network chatter with the database. If you call getBytes, then the driver knows to fetch the whole lot in one go, which is likely to be more efficient.
另一方面,这可能会很慢,这取决于您的 JDBC 驱动程序,因为每次从流中读取都可能需要与数据库进行大量网络通信。如果您调用 getBytes,则驱动程序知道一次性获取全部内容,这可能会更有效率。
getBlob() returns a "pointer" to the data, which you can manipulate using the methods on the Blob interface. If you need to modify or otherwise get fancy with the data in-situ, then this might be best for you.
getBlob() 返回一个指向数据的“指针”,您可以使用 Blob 接口上的方法对其进行操作。如果您需要修改或以其他方式使用原位数据,那么这可能最适合您。
回答by Jason Cohen
Generally you want to pick the stream-based methods (i.e. getBlob().getBinaryStream() or getBinaryStream()) rather than the byte-array method.
通常,您希望选择基于流的方法(即 getBlob().getBinaryStream() 或 getBinaryStream())而不是字节数组方法。
- Performance. The driver has a chance to incrementally pull bytes from the database.
- Memory. You don't have to load all bytes at once, and in one contiguous block.
- 表现。驱动程序有机会从数据库中增量地提取字节。
- 记忆。您不必在一个连续的块中一次加载所有字节。
Worst-case is the database (or JDBC driver) doesn't truly support streaming binary data, but then there's still no appreciable penalty for using the streaming methods.
最坏的情况是数据库(或 JDBC 驱动程序)并不真正支持流二进制数据,但是使用流方法仍然没有明显的惩罚。

