c# - 用于插入值的参数化查询

标签 c# c ms-access oledb

我尝试使用参数化查询将值插入 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/

相关文章:

c# - 具有太多构造函数参数的Unity注入(inject)

c# - 无法将类型 'decimal?' 隐式转换为 'decimal' 。

c# - 未知 url 的 MVC 3 路由

c - 这个错误描述在 fread() 中意味着什么

java - 通过迭代插入记录以不规则顺序创建记录

c# - 如何从 IIS 上托管的 .net 代码访问 key 保管库 secret

java - 近似合适的图像大小

c - 了解 C 中的 addLast 方法

c# - 连接时 Jet.OLEDB 的 "Could not find installable ISAM"。打开

ms-access - MS Access - 后端文件及其包含的文件夹所需的最低权限是什么