MySqlDataReader GetBytes缓冲区问题... [英] MySqlDataReader GetBytes buffer issue...

查看:229
本文介绍了MySqlDataReader GetBytes缓冲区问题...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现MySqlDataReader.GetBytes实现一个奇怪的怪癖,只是想知道这是否众所周知,因为我似乎在网上找不到关于它的任何文章.

I've found a curious quirk of the MySqlDataReader.GetBytes implementation and just wondering if this is well known as I can't seem to find any articles about it on the net.

如果您遵循的代码示例SqlDataReader 并将其应用于MySqlDataReader,它将无法正常工作...除非要检索的记录中的字节数完全可以被缓冲区整除.因此,例如,如果您在循环的最后一次迭代中,只剩下100个字节,但是它试图读取另外1024个字节,则MySqlDataReader将失败并引发异常. SqlDataReader不会.

If you follow the code example for the SqlDataReader and apply it to the MySqlDataReader it wont work...unless the number of bytes in the record you are retreiving is exactly divisible by the buffer. So for example if you are on the last iteration of the loop and there is only 100 bytes left but it's trying to read another 1024 bytes then the MySqlDataReader will fail and throw an exception. The SqlDataReader will not.

除非我做错了什么?

D.

推荐答案

与其读取整个缓冲区的大小,不如仅请求 缓冲区的大小,而且还要求您相信剩下的最大大小.老实说,您最好还是创建一个大小完全合适的缓冲区,而不是一个固定大小的缓冲区.

Rather than reading the whole buffer size, only ask for at most the buffer size, but also at most what you believe is left. To be honest, you might as well create a buffer of exactly the right size rather than a fixed size one anyway.

// I assume this works for MySqlDataReader too...
int length = (int)reader.GetBytes(column, 0, null, 0, 0);
byte[] buffer = new byte[length];
int index = 0;

while (index < length)
{
    int bytesRead = (int)reader.GetBytes(column, index,
                                    buffer, index, length - index);
    index += bytesRead;
}

但是,如果您希望使用较小的缓冲区(例如,一次要处理一个缓冲区),则可以使用:

But if you wanted a smaller buffer (e.g. if you were processing it a buffer at a time) you could use:

int length = (int)reader.GetBytes(column, 0, null, 0, 0);
byte[] buffer = new byte[length];
int index = 0;

while (index < length)
{
    int bytesRead = (int)reader.GetBytes(column, index, buffer, 0, 
                                    Math.Max(buffer.Length, length - index));
    // Process the buffer, up to value bytesRead
    // ...
    index += bytesRead;
}

这篇关于MySqlDataReader GetBytes缓冲区问题...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆