简体   繁体   English

如何检查值是否已经存在

[英]How to check if value already exists

I am trying to find a lot of time how to check if value exists and I can not find it, I need to check it twice: 我试图花很多时间检查值是否存在并且找不到,我需要检查两次:

  1. in the sign up 在注册
  2. in the log in 在登录

Here is my code block: 这是我的代码块:

SqlConnection c = new SqlConnection(str);
        SqlCommand cmdUsername = new SqlCommand("SELECT 1 FROM Users WHERE UserName = @userName;", c);
        cmdUsername.Parameters.AddWithValue("userName", userName);
        cmdUsername.CommandType = System.Data.CommandType.Text;
        SqlCommand cmdEmail = new SqlCommand("SELECT 1 FROM Users WHERE Email = @email;", c);
        cmdUsername.Parameters.AddWithValue("email", email);

        c.Open();
        nameExists = (int)cmdUsername.ExecuteScalar();
        emailExists = (int)cmdEmail.ExecuteScalar();
        c.Close();

When I am entering an email it marks the line 当我输入电子邮件时,它标记了该行

emailExists = (int)cmdEmail.ExecuteScalar();

And in the log in all is ok. 并且在登录中一切正常。

Please help me! 请帮我! Thank you all. 谢谢你们。

Assuming you want to prevent duplicate User Name or Email you have to do the following. 假设您要防止重复的用户名或电子邮件,则必须执行以下操作。 1. Set the ID column as INT and set it to Identity column from column properties. 1.将ID列设置为INT,然后从列属性中将其设置为Identity列。 2. Set your Email or User Name as primary key to prevent either Email or User Name from duplication, The best practice is to make the Email column as primary key where there are a lot of cases that the users have same name but with unique emails. 2.将“电子邮件”或“用户名”设置为主键,以防止重复发送“电子邮件”或“用户名”。最佳做法是在许多情况下,用户具有相同的名称,但具有唯一的电子邮件,将“电子邮件”列作为主键。 FYI

Hope that helps! 希望有帮助!

And to check whether username or email exist already here how you do it! 并在此处检查用户名或电子邮件是否已经存在!

SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = @user || [email] = @email)" , c);
check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
check_User_Name.Parameters.AddWithValue("@email", txtBox_Email.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();

if(UserExist > 0)
{
   //Username exist
}
else
{
   //Username doesn't exist.
}

Using your code, just optimized it a bit. 使用您的代码,对其进行一些优化。

  • Just one call to database 只需一次拨打数据库
  • Always close the connection even if a exception occurs 即使发生异常也始终关闭连接
  • Returns false when not found or na exception occurs, true otherwis 未找到或发生异常时返回false,否则返回true

You can also add a check to the password if this is a login check. 如果这是登录检查,则还可以在密码中添加检查。

public bool ValidData(string username, string email, string connectionString)
{
    var c = new SqlConnection(connectionString);
    var cmdUsername = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName = @userName AND email = @email;", c);
    cmdUsername.Parameters.AddWithValue("userName", username);
    cmdUsername.CommandType = System.Data.CommandType.Text;
    cmdUsername.Parameters.AddWithValue("email", email);

    c.Open();
    try
    {
        return (int) cmdUsername.ExecuteScalar() > 0;
    }
    catch (Exception ex)
    {
        //log exception

        return false;
    }
    finally
    {
        c.Close();
    }
}

If you just need the username or the email change: 如果您只需要用户名或电子邮件更改:

    var cmdUsername = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName = @userName AND email = @email;", c);

to: 至:

    var cmdUsername = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName = @userName OR email = @email;", c);

Try this - 尝试这个 -

string myConnection=str;//this is your connection string
string userName="";
string email="";
string parameteruserName = "";//your parameter should goes here
string parameterEmail = "";//your parameter should goes here
try
{
    SqlDataReader myReader = null;
    SqlCommand    myCommand = new SqlCommand(SELECT COUNT(*) as count FROM  Users WHERE UserName =" +parameteruserName+" or  Email ="+parameterEmail 
   )  "+  ";", 
                                             myConnection);
    myReader = myCommand.ExecuteReader();
    while(myReader.Read())
    {
      userName=  myReader["count"].ToString();

    }
myReader.close();
myConnection.Close();
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}


if(Convert.ToInt32(userName)>0){
//your user name is exists
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM