Retrieve LONGBLOB from MySQL in C#

前端 未结 2 483
执念已碎
执念已碎 2020-12-21 13:37

I want to retrieve a LONGBLOB from my MySQL database but I don\'t know how. I have searched the interwebz and nothing really helpful (understandable) was found. When I retri

2条回答
  •  梦毁少年i
    2020-12-21 14:24

    I actually did this as part of a project I was working on...

    public Bitmap loadImage(int imgID)
            {
    
                MySqlDataReader myData;
                MySqlCommand cmd = new MySqlCommand();
    
                string SQL;
                byte[] rawData;
                MemoryStream ms;
                UInt32 FileSize;
                Bitmap outImage;
    
                SQL = "SELECT ImageName, ImageSize, Image FROM Images WHERE ImageID =";
                SQL += imgID.ToString();
    
                try
                {
                    cmd.Connection = connection;
                    cmd.CommandText = SQL;
    
                    myData = cmd.ExecuteReader();
    
                    if (!myData.HasRows)
                        throw new Exception("There are no blobs to save");
    
                    myData.Read();
    
                    FileSize = myData.GetUInt32(myData.GetOrdinal("ImageSize"));
                    rawData = new byte[FileSize];
    
                    myData.GetBytes(myData.GetOrdinal("Image"), 0, rawData, 0, (Int32)FileSize);
    
    
                    ms = new MemoryStream(rawData);
                    outImage = new Bitmap(ms);
                    ms.Close();
                    ms.Dispose();
    
                    myData.Close();
                    myData.Dispose();
    
                    cmd.Dispose();
    
                    return outImage;
    
    
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show(ex.Message);
                    return null;
                }
    
            }
    

    Hope this helps. Also please excuse any bad coding practices, this was written a while ago.

    Thanks Tom

提交回复
热议问题