【问题标题】:How to insert combo box value into Access using C#如何使用 C# 将组合框值插入 Access
【发布时间】:2016-05-18 15:06:55
【问题描述】:

我无法将组合框值输入到数据库中,它说插入查询不能包含多个值,并在 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);
     }
}

【问题讨论】:

    标签: c# sql ms-access combobox oledb


    【解决方案1】:

    来自MSDN - OleDbCommand.CommandText Property

    当 CommandType 设置为 Text 时,OLE DB.NET 提供程序不支持将参数传递给 SQL 语句或由 OleDbCommand 调用的存储过程的命名参数。在这种情况下,必须使用问号 (?) 占位符。例如: SELECT * FROM Customers WHERE CustomerID = ? 因此,OleDbParameter 对象添加到 OleDbParameterCollection 中的顺序必须直接对应参数的问号占位符的位置。

    将您的 CommandText 替换为以下内容:

    cmd.CommandText = "INSERT INTO Films(DVD_No,Films_1,Category_1,SubCategory_1)VALUES(?,?,?,?)";
    

    您已经按正确的顺序添加了参数。祝你好运!

    【讨论】:

    • 非常感谢您的帮助。我已经使用了你所说的,但错误来自组合框。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多