【问题标题】:How to check if a value in a textbox already exists in a connected database如何检查文本框中的值是否已存在于连接的数据库中
【发布时间】:2016-03-06 12:23:47
【问题描述】:

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

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

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

(可能的解决方案 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.

【问题讨论】:

  • 为什么不使用 select count(*) from employee where contact_number='022222' 之类的查询,其中“022222”是您想要的数字,如果 count 为 1,那么它已经存在,否则呢你想要的..
  • 但这不是只对一个号码有效,因为您正在搜索一个特定的号码吗?我还在我的数据库中将 ContactNumber 设为字符串(短文本)。
  • 联系号码是字符串还是数字都没有关系,如果您想搜索多个号码,那么为什么不将其用作 select count(*) from employee where contact_number=addContactNum.Text
  • @user6002727 我正在尝试使用它,但它说语法及其突出显示存在问题:OleDbDataReader dr = cmd.ExecuteReader();
  • 你愿意分享你想要做什么吗?

标签: c# sql visual-studio


【解决方案1】:

从头到尾更新你的功能

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..";
            }
        }
    }

【讨论】:

  • 我已经更新了代码,上面写着:附加信息:查询表达式“ContactNumber =”中的语法错误(缺少运算符)。然后我尝试做@addContactNum.Text
  • 你用什么数据库?
  • 查看更新的答案@JordanCoaten 可能对您有所帮助,这只是检查您的情况,如果您想在 COntactNumber 不存在的情况下保存数据,那么您必须处理 else 语句
  • 感谢您的回答,但我的验证无法正常工作,您的代码是否基本上保存了输入到文本框中的第一个值。我已经通过了它,似乎是这种情况,如果是这样,我该如何编辑?
  • 你有什么问题?你想编辑你的代码吗?
【解决方案2】:

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

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
}

【讨论】:

  • 我已将您的代码添加到方法中并停止调用其他方法,并删除与其他方法链接的布尔变量,但我收到此错误:附加信息:无效的 SQL 语句;预期为“DELETE”、“INSERT”、“PROCEDURE”、“SELECT”或“UPDATE”。
  • 我已经更新了它,但仍然有同样的错误我应该如何给你看代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 2021-10-10
相关资源
最近更新 更多