c# - 从 mysql 检索保存的图像时出现参数无效错误 c#

标签 c# mysql .net winforms visual-studio

我已在表中将图像列创建为 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 引擎应该接受的十六​​进制字符串。

关于c# - 从 mysql 检索保存的图像时出现参数无效错误 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40135030/

相关文章:

java - Swing 表单编辑器

c# - 如何将包含指数数的字符串转换为十进制数并返回字符串

c# - WinForms - 为什么每次我在 Visual Studio 中打开 C# 窗体时都会在其中运行 SQL?

c# - ASP.NET MVC : directly assign value to model inside razor view

c# - 有人可以提炼成正确的英语委托(delegate)是什么吗?

MySQL SUM 查询与连接和联合所有

mysql - 如何修改这个子查询以使其更具体

c++ - 在访问冲突时创建转储文件

在 Visual Studio 2010 64 位中构建时的 C# 应用程序无法正常工作

MYSQL过滤器将行乘以两个id列表