检查Access数据库的用户输入

时间:2016-02-19 14:26:20

标签: c# .net ms-access

我一直在尝试创建一个查询来检查输入的PayrollNo是否已存在于数据文件中,如果是,则按钮(BtnContinue)将用户发送到其他表单。我已经被困了几天所以任何帮助都会很棒,因为我毫无疑问接近我需要的地方。

代码如下,为exe。在BtnContinue_Click

private void BtnContinue_Click(object sender, EventArgs e)
{
    OleDbConnection conn = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False");
    using (OleDbConnection Connstring = new OleDbConnection())
    {
        conn.Open();
        String query = ("SELECT count(*) as PayrollNo FROM [Employee] where PayrollNo = @PayrollNo");
        OleDbCommand dbCmd = new OleDbCommand(query, conn);
        using (OleDbDataReader reader = dbCmd.ExecuteReader())
        {
            if (reader.Read())
            {
                PayrollExists form = new PayrollExists();
                form.Tag = this;
                form.Show(this);
                Hide();
            }
            else
            {
                EmployeeDetails form = new EmployeeDetails();
                form.PassValueFirstName = txtFirstName.Text;
                form.PassValueLastName = txtLastName.Text;
                form.PassValuePayrollNo = txtPayrollNo.Text;
                form.Tag = this;
                form.Show(this);
                Hide();
            }                         
        }
    }

就像我说已经坚持了一段时间,所以任何帮助都会很棒

1 个答案:

答案 0 :(得分:6)

据我所见,您从不@PayrollNo参数及其值添加到您的命令中。

使用ExecuteScalar代替ExecuteReader会更好,因为您的查询会返回一行一行。

dbCmd.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = yourPayrollNo;
// I assumed your column type is Integer

并检查它;

int count = (int)dbCmd.ExecuteScalar();
if(count > 0)
{
   // Exist
}

并且Connstring连接似乎不必要,因为您从未在代码中使用它。将其替换为上面一行定义的conn

作为一个完整的例子;

var conStr = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using(var conn = new OleDbConnection(conStr))
using(var dbCmd = conn.CreateCommand())
{
   dbCmd.CommandText = "SELECT count(*) FROM [Employee] where PayrollNo = @PayrollNo";
   dbCmd.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = yourPayrollNo;

   conn.Open();
   int count = (int)dbCmd.ExecuteScalar();
   if(count > 0)
   {
      PayrollExists form = new PayrollExists();
      form.Tag = this;
      form.Show(this);
      Hide();
   }
   else
   {
      EmployeeDetails form = new EmployeeDetails();
      form.PassValueFirstName = txtFirstName.Text;
      form.PassValueLastName = txtLastName.Text;
      form.PassValuePayrollNo = txtPayrollNo.Text;
      form.Tag = this;
      form.Show(this);
      Hide();
   }      
}

顺便说一句,OleDbCommand does not support named parameters。当您向OleDbCommand添加参数时,唯一的问题就是他们的订单。由于您的示例中只有一个参数,因此这不是问题,但请注意它。