如果存在用户名和密码,请查询数据库并登录
本文关键字:查询 数据库 登录 密码 存在 用户 如果 | 更新日期: 2023-09-27 18:07:53
将数据库添加到web表单项目中。名为Users的数据库表由3列组成。Id、用户名、密码。手动插入数据库中的数据。如果用户在登录页面上插入了正确的用户名和密码,则应该将其重定向到另一个页面。
我的c#代码:using(SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)'v11.0;AttachDbFilename=|DataDirectory|'Database1.mdf;Integrated Security=True"))
{
SqlCommand cmd = new SqlCommand("select * from Users;");
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
con.Close();
}
如何从数据库中获取数据,并检查用户是否输入正确的用户名和密码登录?
理想情况下,密码不应该以明文形式存储(而是应该加盐和散列)。
但是如果它是明文,它将是:
using(SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)'v11.0;AttachDbFilename=|DataDirectory|'Database1.mdf;Integrated Security=True"))
{
SqlCommand cmd = new SqlCommand("select * from Users where username like @username and password = @password;");
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
cmd.Connection = con;
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
bool loginSuccessful = ((ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0));
if (loginSuccessful)
{
Console.WriteLine("Success!");
} else {
Console.WriteLine("Invalid username or password");
}
}
你的方法应该是这样的
string Command = "SELECT Id FROM User WHERE Username = @Username AND Password = @Password;";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand(Command, myConnection))
{
myCommand.Parameters.Add("@Username", tbUser.Text);
myCommand.Parameters.Add("@Password", tbPass.Text);
return myCommand.ExecuteScalar() != null;
}
}
将代码保留在按钮单击事件中。用户在各自的文本框中输入用户名和密码后,单击登录按钮,在该按钮单击事件中给出如下代码。在aspx文件中给标签像
<asp:Label ID="lbluser" runat="server" Visible="false"></asp:Label>
<asp:Label ID="lblpwd" runat="server" Visible="false"></asp:Label>
<asp:Label ID="lblmessage" runat="server" Visible="false" Text="Incorrect Username and Password"></asp:Label>
SqlCommand cmd = new SqlCommand("select * from Users where username=@username and password=@password ", con);
cmd.Parameters.AddWithValue("@username", txtUsername.Text);
cmd.Parameters.AddWithValue("@password", txtPassword.Text);
con.Open();
SqlDataReader dr = default(SqlDataReader);
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while ((dr.Read()) == true)
{
lbluser.Text = dr["UserName"].ToString();
lblpwd.Text = dr["password"].ToString();
if ((txtUsername.Text.Trim() == lbluser.Text.Trim()) &(txtPassword.Text.Trim() == lblpwd.Text.Trim()))
{
Response.Redirect("nextpage.aspx");
}
else
{
lblmessage.Visible = true;
}
}
dr.Close();
con.Close();