简体   繁体   English

从DB检索用户密码

[英]Retrieving user password from DB

I have a table that has a list of user names and passwords and I want to match the the user name and password the user enter with the one saved in the DB. 我有一个包含用户名和密码列表的表,我希望将用户输入的用户名和密码与保存在DB中的用户名和密码相匹配。 The code I am using only retrieves the login information of the first record in the users table, how can I change that so the code would work for all user. 我使用的代码只检索users表中第一条记录的登录信息,如何更改,以便代码适用于所有用户。

I am a beginners at VS and I am trying to learn the basics so later on I will be implementing more complex login page with encryption.. Thank you 我是VS的初学者,我正在尝试学习基础知识,所以稍后我会用加密实现更复杂的登录页面..谢谢

 private void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;

        cn.ConnectionString = "Server=;Database=;User Id=naljalid;Password=";
        cmd.Connection = cn;
        string username = tbxUserName.Text;
        cmd.CommandText = "SELECT UserPassword FROM tblLoginProject WHERE UserName=username";

        // open a connection to DB
        cn.Open();

        //read the table
        dr = cmd.ExecuteReader();

        //read a record from te data reader
         dr.Read();

        // compare the passwords


       if (tbxPassword.Text == dr.GetString(0))
         {
             MessageBox.Show("Hello");
        }

        else
        {
            MessageBox.Show("Login failed, please re-enter your password");
        }
    }

The key to this is the SQL query, specifically the WHERE clause: 关键是SQL查询,特别是WHERE子句:

SELECT UserPassword FROM tblLoginProject

This query will return all the passwords from the database. 此查询将返回数据库中的所有密码。 But you want to retrieve the password of only one user, so you need to implement a WHERE clause 但是您只想检索一个用户的密码,因此需要实现WHERE子句

SELECT UserPassword FROM tblLoginProject WHERE UserName = @username

This query will retrieve the password for only a certain user where the value of the field UserName equals the value passed in the parameter @username. 此查询将仅检索特定用户的密码,其中字段UserName的值等于参数@username中传递的值。 So now we need to make sure to pass that value. 所以现在我们需要确保传递该值。 You can't just include it in the SQL query like you're doing right now. 不能像现在这样在SQL查询中包含它。 We do it like this: 我们这样做:

cmd.Paramateres.AddWithValue("@username", username);

This should work fine, but for best practices you should check for both username and password at the same time: 这应该可以正常工作,但是对于最佳实践,您应该同时检查用户名密码:

SELECT count(*) FROM tblLoginProject WHERE UserName = @username AND UserPassword = @password

Then of course we pass both values: 然后我们当然传递两个值:

cmd.Paramateres.AddWithValue("@username", username);
cmd.Paramateres.AddWithValue("@password", password);

This will return 0 if no users are found with that combination of username and password (invalid login), or more than 0 if such a user was found (valid login). 如果没有找到用户名和密码组合(无效登录)的用户,则返回0;如果找到这样的用户,则返回0(有效登录)。

Next stop you should research hashing passwords. 下一站你应该研究散列密码。 After that would be salting these hashes. 在那之后将腌制这些哈希。 Good luck! 祝好运!

Change the query a tidge to this: 将查询更改为:

cmd.CommandText = "SELECT UserPassword FROM tblLoginProject WHERE UserName = @username";

and then set that parameter value: 然后设置该参数值:

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

That will get you the row for the user you're looking for. 这将为您找到您正在寻找的用户的行。 Now on to a few more recommendations. 现在再提几点建议。 The ADO.NET classes implement the IDispoable interface. ADO.NET类实现了IDispoable接口。 That interface identifies that the class uses some unmanaged resources. 该接口标识该类使用一些非托管资源。 You want to make sure those get disposed. 你想确保那些被处置。 Consider the following rewrite of your current code: 考虑以下重写当前代码:

using (SqlConnection cn = new SqlConnection("Server=;Database=;User Id=naljalid;Password="))
using (SqlCommand cmd = new SqlCommand("SELECT UserName FROM tblLoginProject WHERE UserName = @username AND Password = @password", cn))
{
    cn.Open();

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

    var result = cmd.ExecuteScalar() as string;
    if (string.IsNullOrEmpty(result))
    {
        // user was not found
    }
    else
    {
        // user was found
    }
}

It leverages the using statement to ensure that the objects get disposed. 它利用using语句来确保对象被处置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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