【问题标题】:MySQL .NET Connector documentation confusionMySQL .NET 连接器文档混乱
【发布时间】:2010-12-08 14:52:40
【问题描述】:

MySQL 5.0 Connector.NET Examples 状态:

GetBytes 返回字段中的可用字节数。在大多数情况下,这是字段的确切长度。

但是,MySQL 5.0 Connector.NET DocumentationGetBytes 的返回值列为读入缓冲区的字节数。

对我来说,这根本不是一回事!

无论如何,我的问题是:将内容从数据源获取到MemoryStream 对象的最易读的结构是什么?我正在使用来自GetBytes 的返回值来增加GetBytes 方法的数据索引参数,但似乎我一直在超出该字段,因为我得到IndexOutOfRangeException 被抛出。

【问题讨论】:

标签: .net mysql blob mysql-connector


【解决方案1】:

我同意 MySqlDataReader 的文档还有很多不足之处。

当您将null 作为buffer 参数传递时,GetBytes 返回字段的总长度。当您传递非空的 buffer 参数时,GetBytes 返回写入缓冲区的字节数。

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

【讨论】:

    【解决方案2】:

    我稍微修改了卢克的代码(并投了赞成票)。不是说更好,只是不同。仅适用于小于 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;
    }
    

    如果你愿意,你可以把它变成一个扩展方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-15
      • 2012-03-14
      • 2011-04-04
      • 1970-01-01
      • 2021-02-15
      • 2017-09-05
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多