简体   繁体   中英

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

I have created image column in table as mediumblob

to save image i used following code

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

and it was sucessfull but m getting parameter invalid while retrieving it to picture box using below code

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

searched many forums and tired all they suggesting in every posts but im unable to solve..

You don't saving image into DB correctly. Line string qry = "Update admin_info set ``img``='"+ ImageData + "' where id='AD001"; will result in qry = "Update admin_info set ``img``='System.Byte[]' where id='AD001 because you are converting byte array to string which will result in type name only. You will have to convert byte array to HEX string which should be accepted by SQL engine.

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

This solved my probelm and im able to retrive too.. Thanks Honz for pointing out the actual problem for converting it to sting :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM