[英]Check if username is in the database using ASP.Net
I want to check if a username is already in the database. 我想检查用户名是否已经在数据库中。 It comes along with my update statement. 它与我的更新语句一起提供。 I have this code and I do not know where to put the select statement: 我有以下代码,但我不知道将select语句放在哪里:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "update UserData set Password=@Password where UserName='" + txtUser.Text + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar));
com.Parameters["@Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text);
com.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
con.Close();
}
I want something like 我想要类似的东西
"Select Username from Userdata Where Username = txtUser.Text"
You don't need a SELECT
here. 您不需要在这里进行SELECT
。 ExecuteNonQuery()
returns the number of rows affected, which means that when it returns 0, there was no user with the given name in the database. ExecuteNonQuery()
返回受影响的行数,这意味着当它返回0时,数据库中没有使用给定名称的用户。 If all went well, it should return 1. 如果一切顺利,它应该返回1。
Your code is vulnerable to SQL injection and leaks resources. 您的代码容易受到SQL注入的攻击,并会泄漏资源。 Here's a better version: 这是一个更好的版本:
protected void btn_update_Click(object sender, EventArgs e)
{
using(var con = new SqlConnection(conn))
{
con.Open();
var commandTest = "update UserData set Password=@Password where UserName=@Username";
using(var com = new SqlCommand(commandTest, con))
{
com.Parameters.AddWithValue("@Username", txtUser.Text);
com.Parameters.AddWithValue("@Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
if(com.ExecuteNonQuery() == 1)
{
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.