【问题标题】:Parameter Not Valid Error c# while retriving saved image from mysql从mysql检索保存的图像时参数无效错误c#
【发布时间】:2016-10-20 00:09:07
【问题描述】:

我在表中创建了图像列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
               }
         }
     }         

搜索了很多论坛,厌倦了他们在每个帖子中提出的所有建议,但我无法解决..

【问题讨论】:

标签: c# mysql .net winforms visual-studio


【解决方案1】:

您没有将图像正确保存到数据库中。 行string qry = "Update admin_info set ``img``='"+ ImageData + "' where id='AD001"; 将导致 qry = "Update admin_info set ``img``='System.Byte[]' where id='AD001 因为您将字节数组转换为字符串,这将导致仅类型名称。 您必须将字节数组转换为 SQL 引擎应该接受的 HEX 字符串。

【讨论】:

  • 感谢指出..我使用sql参数qry解决了它
【解决方案2】:
        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 指出将其转换为刺痛的实际问题:)

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多