c# - 如何检查记录是否已存在于 SQL 数据库中?

标签 c# sql sql-server

我正在尝试检查该值是否存在于数据库列中。我知道这个问题被问过好几次,但没有一个能解决我的问题。我已经尝试了很多方法。无论如何,我的以下代码都是异常的;

"An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll Additional information: No mapping exists from object type System.Windows.Forms.TextBox to a known managed provider native type."

此问题已解决,这是一个错误的异常。但它仍然无法正常工作,尽管记录在数据库中,但它并不限制我。

谁能告诉我我的代码有什么问题,代码是;

private void btn_Register_Click(object sender, EventArgs e)
    {
        lbl_Available.Visible = false;
        lbl_Empty.Visible = false;
        bool hasValue1 =  string.IsNullOrWhiteSpace(txt_PinCode.Text);
        bool hasValue2 =  string.IsNullOrWhiteSpace(txt_Name.Text);
        if (!hasValue1 && !hasValue2)
        {
            string pincode = txt_PinCode.Text;
            if (UserExists(pincode))
            {
               lbl_Available.Visible = true;
               return;
            }
            else
            {
                this.Hide();
                RegCluePoint frm = new RegCluePoint();
                frm.lbl_PinCode.Text = txt_PinCode.Text;
                frm.lbl_Name.Text = txt_Name.Text;
                frm.Show();
            }                    
        }
        else
        {
            lbl_Empty.Visible = true;
        }
    }
private bool UserExists(string pincode)
    {
        //pincode = txt_PinCode.Text
        //SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "SELECT PINCODE from UserInput where PINCODE = '@pincode'";
        cmd.Parameters.AddWithValue("PINCODE", pincode);
        if (conn.State != ConnectionState.Open)
        conn.Open();

        string pinString = (string)cmd.ExecuteScalar();
        conn.Close();

        return (pinString != null);
    } 

最佳答案

您正在发送 txt_PinCode,这是一个文本框对象,而不是此行中的字符串 (txt_PinCode.Text) cmd.Parameters.AddWithValue("PINCODE", txt_PinCode);

关于c# - 如何检查记录是否已存在于 SQL 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30884362/

相关文章:

c# - FormClosing() 事件加载了两次

c# - 从 paypal 结帐返回后在 firefox 中丢失 session

sql - 为什么 Oracle SQL 不允许我们在条件中使用别名?

sql-server - T-SQL 存储过程 - 检测参数是否作为 OUTPUT 提供

javascript - 将 JSON 保存到 SQL

python - 重置滚动总和

c# - 获取 .Net XML 文档以返回字典的特定类型

c# - 在 C# 中使用 Moq 模拟服务

mysql - 如何使用 `IN` 运算符获取计数

c# - 如何将 SqlBulkCopy 与 SMO 和事务结合使用