C# Mysql datareader - 如何使用 datareader 获取其他列

C# Mysql datareader - how to get other coloumn using datareader

我正在尝试从我的数据库中验证经过散列和加盐处理的密码。我在我的用户 table 用户名、散列和盐中创建了一个列。现在我想知道我可以使用 DataReader 访问其他列值。

我试过这个方法但是我得到了一条红线。这也是我失败的尝试

    public static bool VerifyPassword(string enteredPassword, string storedHash, string storedSalt)
{

    var saltBytes = Convert.FromBase64String(storedSalt);
    var rfc2898DeriveBytes = new Rfc2898DeriveBytes(enteredPassword, saltBytes, 10000);
    return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256)) == storedHash;

}


private void bunifuFlatButton1_Click(object sender, EventArgs e)
{

    string userhash;
    string usersalt;

    MySqlConnection mysqlCon = new MySqlConnection(connectionString);
    MySqlCommand cmd = new MySqlCommand("SELECT * FROM login.info WHERE username = @user", mysqlCon);
    MySqlDataReader rd;
    rd = cmd.ExecuteReader();
    cmd.Parameters.Add("@user", MySqlDbType.VarChar).Value = username.Text;
    mysqlCon.Open();

    while (rd.Read())
    {

        userhash = rd.GetString("hash");
        usersalt = rd.GetString("salt");

        bool isPasswordMatched = VerifyPassword(textpass.Text, userhash.Hash, usersalt.Salt);
// i got redline error in here. i only follow instruction.. link below
        if (isPasswordMatched)
        {
            //Login Successfull
        }
        else
        {
            //Login Failed
        }
    }
}

顺便说一句,我只遵循此线程中的此说明。

这是编写代码的另一种方式,不是真正的答案,但...不是完美的头脑,但至少它会处理对象并以正确的顺序调用它们。请阅读 IDisposable 和 Sql Injection。

private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
    using (MySqlConnection mysqlCon = new MySqlConnection(connectionString))
    {
                               // Use a named list of fields please. And cleanse the text.
        using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM login.info WHERE username = @user", mysqlCon))
        {
            cmd.Parameters.Add("@user", MySqlDbType.VarChar).Value = username.Text; // Let's hope user name is not Jimmy DropTables!!
            mysqlCon.Open();

            using (MySqlDataReader rd = cmd.ExecuteReader())
            {
                while (rd.Read())
                {
                    string userhash = rd.GetString("hash");
                    string usersalt = rd.GetString("salt");

                    bool isPasswordMatched = VerifyPassword(textpass.Text, userhash, usersalt);
                    // Note that we are passing in strings, not props of an unknown object
                    if (isPasswordMatched)
                    {
                        //Login Successfull
                    }
                    else
                    {
                        //Login Failed
                    }
                }
            }

            mysqlCon.Close();
        }
    }
}