无法检查用户是否已存在于我的数据库中

时间:2019-05-04 05:03:36

标签: c# html css asp.net visual-studio

我开始学习ASP.NET。我创建了一个注册系统,当我尝试检查数据库中是否已经存在用户名或电子邮件时,即使您已经拥有用户名或电子邮件,也不会对其进行检查并创建用户。

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();
}

谢谢!

4 个答案:

答案 0 :(得分:1)

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;

让SQL Server检查是否存在匹配项将在第一个匹配项处停止,而不是可能返回一组匹配项,然后简单地相应地返回一个值。这样可以最大程度地减少服务器与软件之间传输的数据,并避免在我们只在乎是否有匹配项时进行计数。

答案 1 :(得分:0)

无论何时要查找TRUE / FALSE值或不计算任何记录,都始终使用COUNT(1)。

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

检查用户是否已经存在

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