簡體   English   中英

從MySQL檢索保存的圖像時參數無效錯誤C#

[英]Parameter Not Valid Error c# while retriving saved image from mysql

我在表中創建了mediumblob作為mediumblob

保存圖像我用下面的代碼

byte[] ImageData;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
ImageData = new byte[Convert.ToInt32(fs.Length)];
fs.Read(ImageData, 0, Convert.ToInt32(fs.Length));
fs.Close();

string qry = "Update admin_info set `img`='"+ ImageData + "' where id='AD001";

using (con = new MySqlConnection(DBConStr))
{
    con.Open();
    using (cmd = new MySqlCommand(qry, con))
    {
         cmd.ExecuteNonQuery();
    }
}
    MessageBox.Show(" Profile Picture Updated Successfully!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

它是成功的,但是使用以下代碼將其檢索到圖片框時獲取參數無效

using (MySqlConnection conn = new MySqlConnection("Server = localhost; Port = 3307; database = attendance; uid = root; pwd = MJN45720!"))
{
     conn.Open();
     string myQuery = "SELECT img FROM admin_info where id='AD001'";

     using (MySqlCommand cmd = new MySqlCommand(myQuery, conn))
     {
         using (var reader = cmd.ExecuteReader())
         {
              while (reader.Read())
              {
                   byte[] x = (byte[])reader["img"];
                   MemoryStream ms = new MemoryStream(x);
                   pictureBox1.Image = new Bitmap(ms); //Parameter invalid in this line
               }
         }
     }         

搜索了很多論壇,厭倦了他們在每個帖子中建議的所有內容,但即時通訊無法解決。

您沒有將圖像正確保存到數據庫中。 string qry = "Update admin_info set ``img``='"+ ImageData + "' where id='AD001"; 將導致qry = "Update admin_info set ``img``='System.Byte[]' where id='AD001因為您將字節數組轉換為僅會產生類型名稱的字符串。您將必須轉換字節數組到應由SQL引擎接受的十六​​進制字符串。

        byte[] ImageData;
        fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        br = new BinaryReader(fs);
        ImageData = br.ReadBytes((int)fs.Length);
        br.Close();
        fs.Close();

       using (con = new MySqlConnection(DBConStr))
        {
            con.Open();
            using (cmd = new MySqlCommand(qry, con))
            {
                cmd.Parameters.Add("@pimage", MySqlDbType.Blob);
                cmd.Parameters["@pimage"].Value = ImageData;
                cmd.ExecuteNonQuery();
            }
        }      

這解決了我的問題,也無法檢索。.感謝Honz指出了將其轉換為sting的實際問題:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM