什么'长'参数应该怎么传递给SqlDataReader.GetBytes()参数、GetBytes、SqlDataReader

2023-09-04 00:08:06 作者:肌肉小男男惹人爱-

我有一个SqlDataReader,需要使用SqlDataReader.GetBytes()方法,从中读取为varbinary(max)列。这个方法填充一个字节数组,因此需要知道数据的长度来读取。

I have a SqlDataReader and need to read a varbinary(max) column from it using the SqlDataReader.GetBytes() method. This method populates a byte array and therefore needs to know what length of data to read.

这是我感到困惑。显然我想读的所有已在此行/列被返回从数据库中的数据有啥'长'参数我要传递?

This is where I get confused.. Clearly I want to read all the data that has been returned from the database in this row/column so what 'length' parameter should I pass?

据我所看到的,SqlDataReader中没有提供任何方法来发现数据的长度是可用的,所以这种方法似乎相当尴尬的我。

As far as I can see, the SqlDataReader doesn't provide any methods to discover what length of data is available, therefore this method seems fairly awkward to me.

我很想只是传递int.MaxValue这里忘了这个问题,但一些有关这不符合我的权利坐。

I'm tempted to just pass int.MaxValue here and forget about the issue but something about this doesn't sit right with me.

我知道我可以改为调用

byte[] value = (byte[])dataReader["columnName"];

......这似乎完全不搭内部照顾的长短问题。但是我的工作了一套复杂的code生成模板已围绕SqlDataReader.GetXXXX()方法。所以我绑成使用GetBytes会,并需要了解它的正确用法。

.. and this seems to completely take care of the length issue internally. However I am working with a set of complicated code generation templates that have been built around the SqlDataReader.GetXXXX() methods. So I am tied into using GetBytes and need to understand its proper usage.

推荐答案

在与 VARBINARY(最大)交易,有两种情况:

的数据的长度适中 数据的长度为大

的GetBytes()适用于在第二情况下,当您使用 CommandBehaviour.SequentialAccess ,以确保您的流的数据,而不是的缓存的吧。特别是,在此使用您通常将在流写入(例如),在一个循环。例如:

GetBytes() is intended for the second scenario, when you are using CommandBehaviour.SequentialAccess to ensure that you are streaming the data, not buffering it. In particular, in this usage you would usually be writing (for example) in a stream, in a loop. For example:

// moderately sized buffer; 8040 is a SQL Server page, note
byte[] buffer = new byte[8040]; 
long offset = 0;
int read;
while((read = reader.GetBytes(col, offset, buffer, 0, buffer.Length)) > 0) {
    offset += read;
    destination.Write(buffer, 0, read); // push downstream
}

不过!如果您使用的是中等大小的数据,那么你原来的code:

However! If you are using moderately sized data, then your original code:

byte[] data = (byte[])reader[col];

是好的!! 。没有什么不对的做法,实际上是获取* API的坏的在少数情况下 - 的getchar( )是一个明显的例子(提示:它不工作)

is fine!!. There is nothing wrong with this approach, and in fact the Get* API is broken in a few cases - GetChar() being a notable example (hint: it doesn't work).

它的没关系的,你有能使用获取* code - 在这种情况下,中投的做法是完全合适的。

It doesn't matter that you have existing code that uses Get* - in this case, the cast approach is perfectly appropriate.

 
精彩推荐
图片推荐