我有一个名为 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/