-1

I have little problem here. I try to use SqlDataReader to read data from my database. Code is like this:

        internal static User GetUser(string login)
    {
        SqlConnection conn = new SqlConnection(DataBaseUtility.ConnectionString);

        conn.Open();

        string sql = "SELECT * FROM BookMenagerDB.dbo.users";
        //where UserLogin like @login
        try
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@login", login);
            User user = new User();
            SqlDataReader sqlDataReader = cmd.ExecuteReader();
            user.Id = (int)sqlDataReader["UserId"];
            user.Login = sqlDataReader["UserLogin"].ToString();
            user.PasswordHash = sqlDataReader["UserPassword"].ToString();
            user.Salt = (byte[])sqlDataReader["UserPasswordSalt"];
            return user;
        }

        catch (SqlException ex)
        {
            MessageBox.Show("GetUser fail");
        }
        conn.Close();
        return new User();
    }

I try sql query and I get data but line "user.Id = (int)sqlDataReader["UserId"];" show me there is no data in sqlDataReader. I have no idea what the problem is.

enter image description here

2 Answers2

3

You need to call the Read() function on your SqlDataReader to advance the reader to the first or next record from the database. Also you should use disposing to release connection and resources.

public User GetUser(string login)
{
    User user = new User();
    const string sql = "SELECT * FROM BookMenagerDB.dbo.users";
    using (SqlConnection connection = new SqlConnection(DataBaseUtility.ConnectionString))
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        connection.Open();
        command.Parameters.AddWithValue("@login", login);
        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                user.Id = (int)reader["UserId"];
                user.Login = reader["UserLogin"].ToString();
                user.PasswordHash = reader["UserPassword"].ToString();
                user.Salt = (byte[])reader["UserPasswordSalt"];
            }
        }
    }
    return user;
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
mr.coffee
  • 962
  • 8
  • 22
0

After ExecuteReader() you should Read() to get records:

   User user = new User();
   SqlDataReader sqlDataReader = cmd.ExecuteReader();
   if(sqlDataReader.Read())
   {
       user.Id = (int)sqlDataReader["UserId"];
       user.Login = sqlDataReader["UserLogin"].ToString();
       user.PasswordHash = sqlDataReader["UserPassword"].ToString();
       user.Salt = (byte[])sqlDataReader["UserPasswordSalt"];
    }
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171