MySQL .NET Connector documentation confusion

MySQL 5.0 Connector.NET Examples states:

GetBytes returns the number of available bytes in the field. In most cases this is the exact length of the field.

However, MySQL 5.0 Connector.NET Documentation lists the return value of GetBytes as the number of bytes read into the buffer.

To me this isn't the same thing at all!

Regardless, my question is: what's the most readable construction to get the content from the datasource into a MemoryStream object? I'm using the return value from GetBytes to increment the data index parameter of the GetBytes method but seemingly I keep overrunning the field because I get IndexOutOfRangeException being thrown.


I agree that the documentation for MySqlDataReader leaves a lot to be desired.

When you pass null as the buffer argument, GetBytes returns the total length of the field. When you pass a non-null buffer argument, GetBytes returns the number of bytes that were written into the buffer.

long length = yourReader.GetBytes(columnOrdinal, 0, null, 0, 0);
long offset = 0;
var buffer = new byte[4 * 1024];    // 4KB buffer
var ms = new MemoryStream();

while (length > 0)
{
    long bytesRead = yourReader.GetBytes(columnOrdinal, offset, buffer, 0,
                                         (int)Math.Min(length, buffer.Length));

    if (bytesRead > 0)
    {
        ms.Write(buffer, 0, (int)bytesRead);
        length -= bytesRead;
        offset += bytesRead;
    }
}

I modified Luke's code a bit (and upvoted). Not saying it's better, just different. Only works for fields less than 2GB.

private static byte[] ReadBinaryField(MySqlDataReader reader, int fieldIndex)
{
    var remaining = (int)reader.GetBytes(fieldIndex, 0, null, 0, 0);
    var bytes = new byte[remaining];

    while (remaining > 0)
    {
        var offset = bytes.Length - remaining;
        var bytesRead = (int)reader.GetBytes(fieldIndex, offset, bytes, offset, remaining);
        if (bytesRead == 0)
        {
            // Hopefully this is impossible
            throw new Exception("Could not read the rest of the field.");
        }
        remaining -= bytesRead;
    }
    return bytes;
}

You could make it an extension method, if you like.

链接地址: http://www.djcxy.com/p/60966.html

上一篇: .NET MySQL连接器冲突的DbProviderFactories

下一篇: MySQL .NET Connector文档混淆