Problem assigning a SqlParameter-Collection of common programming errors
Hello every1, I have the following function to read records from a Table:
public ArrayList LeerDatos(int pNumero)
{
ArrayList libros = new ArrayList();
string strSql = "Select codLibro, nombreLibro, ubicacion, comentarios, ";
strSql += "idioma, editorial, fechaPublicacion, fechaAlta from Libro ";
cmd.CommandText = strSql;
cmd.Connection = conn;
cmd.Parameters.Clear();
if (pNumero != 0)
{
strSql += " where codLibro = @CODIGO";
cmd.Parameters.Add(new SqlParameter("@CODIGO", pNumero));
}
strSql += " order by codLibro";
SqlDataReader reader;
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
LibroBO libro = new LibroBO();
libro.CodLibro = reader.GetInt32(0);
libro.NombreLibro = reader.GetString(1);
libro.Ubicacion = reader.GetString(2);
libro.Comentarios = reader.GetString(3);
libros.Add(libro);
}
conn.Close();
return (libros);
}
Well, I think it doesn´t have any extrange… it is simply this: when I need all the table records, I pass 0 (zero) to the function parameter. When I need a certain record, I pass the record key.Then, inside the function, I ask if the parameter isn’t zero, in which case I’ll add a parameter to my SqlCommand variable:
if (pNumero != 0)
{
strSql += " where codLibro = @CODIGO";
cmd.Parameters.Add(new SqlParameter("@CODIGO", pNumero));
}
Has it sense? I guess yes.But the problem that I have is that I always get all the records from table. I had executed step by step and I have seen that the previous code is executing right, but the parameter is not having any effect on the query results. Does somebody knows what is going wrong?Thank you