从c#插入数据库

时间:2018-01-17 16:47:58

标签: c# winforms ms-access odbc sql-insert

我使用这段代码已经很久没有问题了。但是,现在当我尝试插入数据库时​​,我收到此错误

  

错误[07002] [MICROSOFT] ODBC MICROSOFT ACCESS DRIVER]预计参数不足2。

有人能让我知道我做错了吗?

if (txtFullName.Text == "" || txtPostcode.Text == "")
{
    MessageBox.Show("Please enter appropriate details in order to proceed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (txtFullName.Text != "" && txtFullName.Text != "")
{
    OdbcCommand cmd = new OdbcCommand("INSERT INTO [Entry] ([FullName], Postcode) Values(@A, @B)", ConnectDb);
    cmd.Parameters.AddWithValue("@A", "HI");
    cmd.Parameters.AddWithValue("@B", "BY");

    ConnectDb.Open();

    try
    {
        int res = cmd.ExecuteNonQuery();

        if (res > 0)
        {
           DialogResult dialogResult = MessageBox.Show("New Allocator saved! would you like to exit? ", "Saved", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

           if (dialogResult == DialogResult.Yes)
           {
               //BackToAdminMainMenu();
           }

           if (dialogResult == DialogResult.No)
           {
               //Clear();
           }
       }
   }
   catch (Exception err)
   {
       MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);
   }
   finally
   {
       ConnectDb.Close();
   }
}

1 个答案:

答案 0 :(得分:3)

ODBC不支持命名参数。尝试使用:

"INSERT INTO [Entry] ([FullName], Postcode) Values(?, ?)"

代替