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.