我有一个名为Functions的类,它将存储Insert,Update和Delete函数。问题是我无法弄清楚如何传递图像(我从图片框中获取)。这是我尝试过的: 函数类:
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);
}
以下是错误消息:
未处理的类型' MySql.Data.MySqlClient.MySqlException' 发生在MySql.Data.dll
中其他信息:字段'图像'没有默认值
答案 0 :(得分:1)
在查询中使用参数非常简单。首先,使用占位符为参数准备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 ?
}