如何检查连接的数据库中是否已存在文本框中的值

时间:2016-03-06 12:23:47

标签: c# sql visual-studio

所以我目前对我的程序的逻辑感到困惑,我已经多次尝试过,但我不太确定。我基本上希望能够通知用户说他们输入的联系号码已经存在于数据库中。我已经接近了我肯定,因为我做了很多研究,但我不认为我所做的实际上是检查数据库,而只是告诉它匹配文本框中的任何内容而不是检查数据库。 / p>

只是为了澄清我不想要从数据库中提取数据并将其放入文本框中。感谢。

更新:针对两种不同建议解决方案的两个不同程序。

(可能的解决方案1)更新的联系电话号码是使用COUNT的唯一方法:

private void CheckContactNumber()
{
    string checkContactNum = "SELECT COUNT(*) FROM Employee WHERE ContactNumber = " + addContactNum.Text + " "; //01234567890

    OleDbCommand cmd = new OleDbCommand(checkContactNum, conn);
    conn.Open();
    OleDbDataReader dr = cmd.ExecuteReader();

    if (dr.Read())
    {
        int countDup = (int)dr[0];

        if (countDup > 0 && addContactNum.Text != "")
        {
            err += "Contact number is already listed in the database\r\n";
            errorContactNum.Visible = true;
            uniqueContactNumber = false;
        }
        else if (countDup == 0 && addContactNum.Text != "")
        {
            errorContactNum.Visible = false;
            uniqueContactNumber = true;
        }
    }

    conn.Close();
}

(可能的解决方案2)更新到第二个建议的解决方案:

if (err == "")
{
    // you miss s here
    string addEmployee = "if not exists(select LastName from Employee where LastName = @LastName)INSERT INTO Employee(FirstName, LastName, Role, DateOfHire, ContactNumber)" +"VALUES(@FirstName, @LastName, @Role, @DateOfHire, @ContactNumber)";

    OleDbCommand cmd = new OleDbCommand(addEmployee, conn);
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    cmd.Parameters.Add("@FirstName", OleDbType.VarChar).Value = addFirstName.Text;
    cmd.Parameters.Add("@LastName", OleDbType.VarChar).Value = addLastName.Text;
    cmd.Parameters.Add("@Role", OleDbType.VarChar).Value = addRole.Text;
    cmd.Parameters.Add("@DateOfHire", OleDbType.VarChar).Value = addDateOfHire.Text;
    cmd.Parameters.Add("@ContactNumber", OleDbType.VarChar).Value = addContactNum.Text;

    conn.Open();

    // i removed the duplicated code
    if (cmd.ExecuteNonQuery() != 1)
    {
        err += "Contact number is already listed in the database\r\n";
                errorContactNum.Visible = true;
    }

    conn.Close();

    addFirstName.Text = String.Empty;
    addLastName.Text = String.Empty;
    addRole.Text = String.Empty;
    addContactNum.Text = String.Empty;
    addRole.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
    }
    //Save It
    else
    {
        MessageBox.Show(err);
    }
}

So this would be acceptable for adding to my database as all criterion is met but it doesnt accept it, I'm assuming it runs the else code right at the bottom of AddEmployee method

Here is an Image of my database which is linked to my program.

2 个答案:

答案 0 :(得分:2)

你可以在一个代码中合并两个代码,在sql server中使用if not exists方法,就像这样

string addEmployee = "if not exists(select LastName from Employee where 
LastName=@LastName)INSERT INTO Employee (FirstName, LastName, Role, 
DateOfHire, ContactNumber)" +"VALUES (@FirstName, @LastName, @Role, @DateOfHire, @ContactNumber)";

if (cmd.ExecuteNonQuery()!=1){
// the employee exist in database
}

答案 1 :(得分:2)

从最后更新您的功能

private void CheckContactNumber()
    {

        string checkContactNum = "SELECT COUNT(*) FROM Employee WHERE ContactNumber = " + addContactNum.Text + " "; //01234567890

        OleDbCommand cmd = new OleDbCommand(checkContactNum, conn);
        conn.Open();
        OleDbDataReader dr = cmd.ExecuteReader();

        //if (dr.Read() && addContactNum.Text != "")
        if (dr.Read())
        {
            int count = (int)dr[0];
            if(count>0)
            {
                err += "Contact number is already listed in the database\r\n";
                errorContactNum.Visible = true;
                uniqueContactNumber = false;
            }

        }

        conn.Close();

    }

更新了答案

    private void CheckContactNumber()
    {

        DataSet myDataSet = new DataSet();


        try
        {
            string strAccessSelect = "select count(*) from Employee where ContactNumber='" + addContactNum.Text + "'";
            OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, conn);
            OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

            conn.Open();
            myDataAdapter.Fill(myDataSet, "Employee");


        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
            return;
        }
        finally
        {
            conn.Close();
        }
        DataTable dt = myDataSet.Tables[0];
        if (dt != null)
        {
            if (int.Parse(dt.Rows[0][0].ToString()) > 0)
            {
                string err = "Contact Number Already exist..";
            }
        }
    }