简体   繁体   中英

Can't make check if user already exists in my database

I started to learn ASP.NET. I create a register system, and when I try to check if the username or email already exists in the database, it's not checked and creates the user even when you have it already.

try
{
    conn.Open();
    bool exists = false;
    string checkuser = "SELECT count(*) FROM accounts WHERE username='" + username.Text + "'";

    SqlCommand cmd2 = new SqlCommand(checkuser, conn);
    cmd2.Parameters.AddWithValue("username", username.Text);

    exists = (int)cmd2.ExecuteScalar() > 0;

    if (exists)
    {
        Response.Write("User already exists");
    }

    string command = "INSERT INTO accounts (username, email, password) VALUES (@username, @email, @password)";

    SqlCommand cmd = new SqlCommand(command, conn);

    cmd.Parameters.AddWithValue("@username", username.Text);
    cmd.Parameters.AddWithValue("@email", email.Text);
    cmd.Parameters.AddWithValue("@password", password.Text);

    cmd.ExecuteNonQuery();
}
catch(Exception)
{
    label_msg.Visible = true;
    label_msg.Text = "Something went wrong....";
    throw;
}
finally
{
    Response.Redirect("/layout.aspx");
    conn.Close();
}

Thanks !

string checkuser = "if exists (select 1 from accounts where username=@username) select 1 else select 0 end";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("@username", username.Text);

bool exists = (int)cmd2.ExecuteScalar() > 0;

Having SQL Server check for the existence of matches will stop at the first match instead of potentially returning a set of matches and then it is simply returning a value accordingly. This will minimize data transferred between the server and your software plus avoid performing a count when we really just care if there are any matches.

每当你想要找到TRUE / FALSE值或计算no记录时,总是使用COUNT(1)。

bool exists = false;
string checkuser = "SELECT count(*) FROM accounts WHERE username=@username;";

SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("@username", username.Text);

object result = cmd2.ExecuteScalar();

if (result != null)
    exists = (Convert.ToInt32(result) == 1) ? true : exists;

if (exists)
{
    Response.Write("User already exists");
}

Check if user Exist already

int exists = 0;
string checkuser = "SELECT count(*) FROM accounts WHERE username='" +username.Text + "'";

SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("username", username.Text);

exists = (int)cmd2.ExecuteScalar();

if (exists>0)
{
    Response.Write("User already exists");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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