【问题标题】:Parameterized query for inserting values用于插入值的参数化查询
【发布时间】:2012-03-13 04:47:17
【问题描述】:

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

例外是

OleDbParameterCollection 只接受非空的 OleDbParameter 类型对象,不接受 String 对象。

我是编程新手;谁能帮忙指出我的错误?

【问题讨论】:

    标签: c# c ms-access oledb


    【解决方案1】:

    您正在尝试将字符串添加到参数集合中。试试这个(将 OleDbType.VarChar, 50 更改为数据库中数据列的实际类型。

    oleDbCommand1.Parameters.Add("@quot", OleDbType.VarChar, 50).Value =  txtquotationno.Text;
    

    查看 msdn 示例:http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter.aspx

    【讨论】:

      【解决方案2】:

      Add 对象的单个参数需要一个 OleDBParameter 对象。你只是在传递字符串和数据。

      一个简单的解决方法是使用AddWithValue 方法:

      oleDbCommand1.Parameters.AddWithValue("?", txtquotationno.Text);
      oleDbCommand1.Parameters.AddWithValue("?", cmbjobcode.Text);
      

      OleDB 并不真正使用参数名称,它是基于索引的,这就是为什么您可以将每个参数的问号作为名称传递。您确实必须确保您的参数与查询语句的顺序相同。

      【讨论】:

        猜你喜欢
        • 2017-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        • 1970-01-01
        • 1970-01-01
        • 2011-09-15
        • 1970-01-01
        相关资源
        最近更新 更多