Is there any difference in using the Read () method of the SqlDataReader object?

4

I'm running the code snippet below, however, I was unsure about the Read() method of the SqlDataReader object.

using (SqlDataReader reader = cmd.ExecuteReader())
{
    if (reader.HasRows)
    {
        if (reader.Read())
        {
             pconfigWS.Usuario = reader["usuario"].ToString();
             pconfigWS.Senha = reader["senha"].ToString();
             pconfigWS.EndConWSPorto = reader["endConWSPorto"].ToString();
        }
    }
}

I would like to know if there is a difference in using While(reader.Read()) , if(reader.Read()) and reader.Read()

I know that the result of the query will be only one line, but I have this doubt.

Does anyone know how to say?

Thank you

    
asked by anonymous 08.02.2017 / 18:30

1 answer

2

Each call to Read() will advance the reading of the search results.

In this case, the difference would be:

//contiuna lendo o próixmo até não houver mais
while (reader.Read())
{
  ...
}

//lê o próximo e me fala se for sucedido...
if (reader.Read())
{
  ...
}

//lê o próximo
reader.Read();

I think it's important to know that if(reader.Read()) will advance to the next record, so the next reader.Read() will be the next record, not the current one.

For example, your song explained:

using (SqlDataReader reader = cmd.ExecuteReader())
{
    if (reader.HasRows) //verifique se o leitor tem dado algum
    {
        if (reader.Read()) //lê os dados - se tiver mais de um registro, não está sendo lido
        {
             pconfigWS.Usuario = reader["usuario"].ToString();
             pconfigWS.Senha = reader["senha"].ToString();
             pconfigWS.EndConWSPorto = reader["endConWSPorto"].ToString();
        }
    }
}

And an example that can give unexpected results:

using (SqlDataReader reader = cmd.ExecuteReader())
{
    List<PConfigWS> resultados = new List<obj>();
    if (reader.Read())
    {
        while (reader.Read())
        {
             var pconfigWS = new PConfigWS();
             pconfigWS.Usuario = reader["usuario"].ToString();
             pconfigWS.Senha = reader["senha"].ToString();
             pconfigWS.EndConWSPorto = reader["endConWSPorto"].ToString();
             resultados.Add(pconfigWS);
        }
    }
}

In this case, the first record would be ignored (because of if(reader.Read() ), which would probably not be the desired result. Using reader.HasRows would be the right way, as you used it.

There are not necessarily 'good practices' between these functions - they are literally the same function, being used in different ways. It all depends on whether you are reading just one record or several.

    
08.02.2017 / 18:53