c# - 从 MySQL 数据库中读取 BLOB 图像

标签 c# .net mysql blob

我在从 MySQL 数据库中读回 blob 时遇到了一些问题。我已经成功地将它插入到数据库中,但似乎无法让它读回。我知道你们中的一些人可能会想“为什么他使用数据库来存储图像的 blob,而不仅仅是文件路径/文件名”,但我想要灵 active ,因为很多这些图像将存储在服务器而不是本地,这优化了效率,并允许我在需要时将图像移动到本地。我遵循了一个(简短的)教程并编写了以下接收 blob 的方法;

public void getBlob(string query, string fileOut)
    {
        if (this.OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, mConnection);

            //the index number to write bytes to
            long CurrentIndex = 0;

            //the number of bytes to store in the array
            int BufferSize = 100;

            //The Number of bytes returned from GetBytes() method
            long BytesReturned;

            //A byte array to hold the buffer
            byte[] Blob = new byte[BufferSize];


            //We set the CommandBehavior to SequentialAccess
            //so we can use the SqlDataReader.GerBytes() method.

            MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

            while (reader.Read())
            {
                FileStream fs = new FileStream(DeviceManager.picPath + "\\" + reader["siteBlobFileName"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);
                BinaryWriter writer = new BinaryWriter(fs);
                CurrentIndex = 0;
                BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0,BufferSize);  

                while (BytesReturned == BufferSize)
                {
                    writer.Write(Blob);
                    writer.Flush();
                    CurrentIndex += BufferSize;
                    BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
                }

                writer.Write(Blob, 0, (int)BytesReturned);
                writer.Flush();
                writer.Close();
                fs.Close();
            }
            reader.Close();

            this.CloseConnection();
        }
    }

我是这样调用它的..

 mDBConnector.getBlob("SELECT siteMapPicture, siteBlobFilename FROM sites WHERE siteID = '" + DeviceManager.lastSite + "'", DeviceManager.picPath + "mappicsite" + DeviceManager.lastSite);


PBSite.BackgroundImage = Image.FromFile(DeviceManager.picPath + "mappicsite" + DeviceManager.lastSite);

但是它在 BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0,BufferSize) 上出错;出现错误“GetBytes 只能在二进制或 GUID 列上调用”。我假设这与我在数据库中的字段类型有关,但是将列更改为二进制类型意味着我必须将其存储为 blob 类型,但我想将文件名保留为常规字符串。有什么我想念的吗?或者另一种方法?

edit1 :我认为 bytesreturned 的第一个参数与读取器中的列有关,将其设置为 0 会给出错误“使用 SequentialAccess 读取先前列的尝试无效”,我将对此进行研究。

edit2 :删除顺序访问给我一个大小为 13 字节的文件,(这可能只是第一行,这就是顺序访问读取所有行的原因?)所以也许我以错误的顺序读取列..

编辑 3:我认为这个错误的原因是我输入数据库的方式。更改此方法后,我的 saveBlob 现在看起来像这样:

public void saveBlob(string filePath, string fileName, string siteID)
    {
        if (this.OpenConnection() == true)
        {

            //A stream of bytes that represnts the binary file
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            //The reader reads the binary data from the file stream
            BinaryReader reader = new BinaryReader(fs);

            //Bytes from the binary reader stored in BlobValue array
            byte[] BlobValue = reader.ReadBytes((int)fs.Length);

            fs.Close();
            reader.Close();


            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = mConnection;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT INTO x (y, z) VALUES (@BlobFile, @BlobFileName)";

            MySqlParameter BlobFileNameParam = new MySqlParameter("@BlobFileName", SqlDbType.NChar);
            MySqlParameter BlobFileParam = new MySqlParameter("@BlobFile", SqlDbType.Binary);
            cmd.Parameters.Add(BlobFileNameParam);
            cmd.Parameters.Add(BlobFileParam);
            BlobFileNameParam.Value = fileName;
            BlobFileParam.Value = BlobValue;



                cmd.ExecuteNonQuery();

            this.CloseConnection();
        }
    }

我已经运行了调试器,并且 blobvalue 和 blobfileparam(@blobfile) 都具有完整大小(大约 150k),但是它在执行查询时出错,出现以下错误;

"unable to cast object of type 'system.byte[]' to type 'system.iconvertible"

我查看了代码并尝试将类型二进制更改为图像,以允许更大的文件,但给出了相同的错误。有人知道这个新信息吗?

编辑 4:修复所有问题。注意到在我的代码中我使用了:

 ("@BlobFile", SqlDbType.Binary);

将这些更改为类型“MySqlDbType”(derp),它允许我选择 blob 的类型。事情终于按预期进行了:)

最佳答案

你试过先简化吗?不要一次读取 BLOB 100 个字节,而是尝试简化您的代码以将所有字节读取到一个文件中。这样您就可以轻松排除数据层问题。

以下文档还建议您将文件大小存储为另一列:Handling BLOB Data With Connector/NET

关于c# - 从 MySQL 数据库中读取 BLOB 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526209/

相关文章:

c# - ODBC 公共(public)语言引用?

c# - 计算最小/最大/平均 ping 响应

c# - 具有离散错误代码的 .NET 异常处理

asp.net - 无效的 resx 文件。找不到文件 ..\..\My Project\Resources.resx

.net - 如何在 .net 框架内的方法上设置断点

c# - 为什么这个 foreach 循环不抛出 "collection was modified"异常?

mysql - sql 双内连接 : using group_concat gives empty result set

c# - 来自 Explorer 的命令行参数在每个空格处拆分

php - 解析、格式化查询结果并将其存储为变量

php - 如何隐藏行但不删除(如回收箱功能)