我无法输入组合框值到数据库,它说插入查询不能包含多个值,并在cmd.ExecuteNonQuery上给出错误。帮我解决这个问题。我只是c#
的新秀2 text box and 2 combo box 2 combo box values
private void Button1_Click(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:/Films/Database/Films/FilmDB/FilmsDB.accdb");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Films(DVD_No,Films_1,Category_1,SubCategory_1)VALUES(@no,@f1,@cat1,@scat1)";
cmd.Parameters.AddWithValue("no", TextBox1.Text);
cmd.Parameters.AddWithValue("f1", TextBox2.Text);
cmd.Parameters.AddWithValue("cat1", ComboBox1.GetItemText(ComboBox1.SelectedItem));
cmd.Parameters.AddWithValue("scat1", ComboBox2.GetItemText(ComboBox1.SelectedItem));
//open con
conn.Open();
//exec cmd
int row = cmd.ExecuteNonQuery();
if (row == 1)
{
MessageBox.Show("Data Stored in the Database");
}
else
{
MessageBox.Show("Error");
}
//close con
conn.Close();
}
catch (Exception c)
{
MessageBox.Show("Record failed" + c.Message);
}
}
答案 0 :(得分:0)
来自MSDN - OleDbCommand.CommandText Property:
当CommandType设置为Text时,OLE DB.NET Provider不支持将参数传递给SQL语句或OleDbCommand调用的存储过程的命名参数。在这种情况下,必须使用问号(?)占位符。例如: SELECT * FROM Customers WHERE CustomerID =? 因此,OleDbParameter对象添加到OleDbParameterCollection的顺序必须直接对应于参数的问号占位符的位置。
使用以下内容替换CommandText:
cmd.CommandText = "INSERT INTO Films(DVD_No,Films_1,Category_1,SubCategory_1)VALUES(?,?,?,?)";
您已按正确的顺序添加了参数。祝你好运!