将数据库添加到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();
}
如何从数据库中获取数据并检查用户是否输入了正确的用户名和密码进行登录?
答案 0 :(得分:2)
理想情况下,密码不应该以明文形式存储(应该使用盐水和散列)。
但如果它是纯文本,那就是:
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");
}
}
答案 1 :(得分:1)
你的方法应该是这样的
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;
}
}
答案 2 :(得分:0)
将代码保留在按钮单击事件中。用户在各自的文本框中输入用户名和密码后,点击登录按钮,在该按钮点击事件中给出如下代码。在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();