MySqlDataReader GetBytes buffer issue…

╄→尐↘猪︶ㄣ 提交于 2019-12-04 04:47:56

问题


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.

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.

Unless I'm doing something wrong?

D.


回答1:


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;
}


来源:https://stackoverflow.com/questions/7703032/mysqldatareader-getbytes-buffer-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!