C# MySql 连接。如何传递图像?

标签 c# mysql database

我有一个名为 Functions 的类,它将存储插入、更新和删除函数。问题是我不知道如何传递图像(我从 picturebox 获得)。这是我尝试过的: 函数类:

 public static Functions Insert(String u, String v, byte[] img)
        {

 String query = string.Format("INSERT INTO example(Name, Description) VALUES ('{0}', '{1}, {2}')", u, v,img);
            MySqlCommand cmd = new MySqlCommand(query, dbConn);

            dbConn.Open();

            cmd.ExecuteNonQuery();

            if (cmd.ExecuteNonQuery() == 1)
            {
                MessageBox.Show("Succesfully added!");

            }

            int id = (int)cmd.LastInsertedId;

            Functions func = new Functions(id,u,v,img);

            dbConn.Close();

            return func;

        }

Form1 中的按钮:

    private void button2_Click(object sender, EventArgs e)
    {

        String u = textBox2.Text;
        String v = textBox3.Text;


        MemoryStream ms = new MemoryStream();
        pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
        byte[] img = ms.ToArray();


        currf = Functions.Insert(u, v, img);
    }

错误消息如下:

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll

Additional information: Field 'Image' doesn't have a default value

最佳答案

在查询中使用参数非常简单。首先,使用参数占位符准备 sql 命令文本。然后将参数添加到 MySqlCommand.Parameters 集合中,最后将所有内容传递给数据库引擎,数据库引擎使用参数集合将数据正确插入到基础表中

// Notice that you are missing the third field (the image one)
// Please replace Image with the correct name of the image field in your table
string query = @"INSERT INTO example (Name, Description, Image) 
                 VALUES (@name, @description, @img";
MySqlCommand cmd = new MySqlCommand(query, dbConn);
cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = u;
cmd.Parameters.Add("@description", MySqlDbType.VarChar).Value = v;
cmd.Parameters.Add("@img", MySqlDbType.Binary).Value = img;
dbConn.Open();
// Do not execute the query two times.
// cmd.ExecuteNonQuery();
if (cmd.ExecuteNonQuery() == 1)
{
    MessageBox.Show("Succesfully added!");
    int id = (int)cmd.LastInsertedId;
    ....
}
else
{
    // failure msg ?
}

关于C# MySql 连接。如何传递图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49830805/

相关文章:

c# - 自定义 WebAPI "Access Denied"响应

c# - 如何在单击行标题时选择整行?

mysql - 由于在 MySQL 中使用保留字作为表名或列名而导致的语法错误

包裹在事务中时,Mysql DDL 查询卡在等待表元数据锁定

database - SQL DataType - 如何存储一年?

.net - ADO.NET 数据模型中的备用/候选键

c# - 在 MySql.Data.EntityFrameworkCore 中找不到 Database SetInitializer

c# - 使用 REST API 发布非英文字母表

java - Spring数据@公式计数查询

尽管返回 ID,MySQL 存储过程仍不插入数据