Should I declare scalar variable?

0

I have a method created in a mapper that I use to verify the username and password for a login, the code is as follows:

    public Usuario buscarUsuarioPorNombreYContrasenia(string xNombre, string xPass)
        {
            var param = new List<SqlParameter>();
            var nombre = new SqlParameter();
            var pass = new SqlParameter();
            nombre.ParameterName = "@nombreUsuario";
            nombre.Value = xNombre;
            param.Add(nombre);
            pass.ParameterName = "@pass";
            pass.Value = xPass;            
            param.Add(pass);
            var con = abrirConexion();
            var reader = select("SELECT * FROM usuario WHERE nombreUsuario = @nombreUsuario AND pass = @pass",CommandType.Text,param,con,null);
 // Se cae pasando esta línea.
            Usuario u = null;
            {
                if (reader.Read())
                {
                    u = cargarUsuario(reader);

                }
                cerrarConexion(con);
                return u;     
            }
        }

As for the database I have the following, if I do the query in SQL Server then it works and returns as expected but instead in Visual it gives me that error and the strange thing is that I have already done those queries previously and have worked, maybe I'm missing something this time.

CREATE TABLE usuario(
idUsuario INTEGER PRIMARY KEY IDENTITY (1,1),
nombreUsuario VARCHAR (50) UNIQUE NOT NULL,
tipoUsuario BIT NOT NULL,
pass VARCHAR (50) NOT NULL,
) 

Here's what the Select method does:

public static SqlDataReader select(string sentencia, CommandType tipoComando, List<SqlParameter> parametros, SqlConnection conn, SqlTransaction trns)
{
    if(conn == null)
    {
        abrirConexion();
    }

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = sentencia;
    cmd.CommandType = tipoComando;
    if(parametros == null)
    {
        cmd.Parameters.AddRange(parametros.ToArray());
    }
    if(conn.State == ConnectionState.Closed)
    {
        conn.Open();
    }
    if(trns != null)
    {
        cmd.Transaction = trns;
    }
    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    return dr;            
}

Thanks in advance.

    
asked by Ccccccccc 28.12.2016 в 01:53
source

1 answer

1

The condition that determines when adding the parameters is not correct:

if(parametros == null) // incorrecto
{
    cmd.Parameters.AddRange(parametros.ToArray());
}

Obviously, you want to say:

if(parametros != null)
{
    cmd.Parameters.AddRange(parametros.ToArray());
}

It makes sense that if you never add the parameters to the cmd object, it would give you the error:

  

Must declare the scalar

    
answered by 28.12.2016 / 19:13
source