我尝试使用参数化查询将值插入 Access 数据库:
private void button1_Click(object sender, EventArgs e)
{
if (validationcontrol())
{
MessageBox.Show(cmbjobcode.SelectedValue.ToString());
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO quotationmastertable (quotationcode ,jobcode , jobpk , sillabordercharges , battabordercharges , driverpayment , rent , extra , total , discount , remark ,amount ) Values (?,?,?,?,?,?,?,?,?,?,?,?) ", oleDbConnection1);
oleDbCommand1.Parameters.Add(txtquotationno.Text);
oleDbCommand1.Parameters.Add(cmbjobcode.Text);
oleDbCommand1.Parameters.Add(cmbjobcode.SelectedValue);
oleDbCommand1.Parameters.Add(int.Parse(txtsilabordercharges.Text));
oleDbCommand1.Parameters.Add(int.Parse(txtbattacharges.Text));
oleDbCommand1.Parameters.Add(int.Parse(txtdriverpayment.Text));
oleDbCommand1.Parameters.Add(int.Parse(txtrent.Text));
oleDbCommand1.Parameters.Add(int.Parse(txtextra.Text));
oleDbCommand1.Parameters.Add(int.Parse(txttotal.Text));
oleDbCommand1.Parameters.Add(int.Parse(txtdiscount.Text));
oleDbCommand1.Parameters.Add(txtremark.Text);
oleDbCommand1.Parameters.Add(int.Parse(txtamount.Text));
oleDbCommand1.CommandType = CommandType.Text;
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();
MessageBox.Show(txtquotationno.Text);
}
}
但我在第一行本身遇到异常:
oleDbCommand1.Parameters.Add(txtquotationno.Text);
异常(exception)是
The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not String objects.
我是编程新手;谁能帮我指出我的错误吗?
最佳答案
Add
对象的单个参数需要 OleDBParameter 对象。您只是传递字符串和数据。
一个简单的修复方法是使用 AddWithValue
方法:
oleDbCommand1.Parameters.AddWithValue("?", txtquotationno.Text);
oleDbCommand1.Parameters.AddWithValue("?", cmbjobcode.Text);
OleDB 并不真正使用参数名称,它是基于索引的,这就是为什么您可以将每个参数的问号作为名称传递。您确实必须确保您的参数与查询语句的顺序相同。
关于c# - 用于插入值的参数化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9401888/