Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

must declare the scalar variable @

For some reason after defining my variables I am still getting the 'must declare the scalar variable' error..

using (OleDbConnection conn = new OleDbConnection(connString))
{
    conn.Open();

    using(OleDbCommand cmd = new OleDbCommand("SELECT UserID FROM tblUser WHERE Username=@user AND Password = @pass", conn))
    {
        cmd.Parameters.AddWithValue("@user", user);
        cmd.Parameters.AddWithValue("@pass", pass);

        int UserID = (int)cmd.ExecuteScalar();

        return UserID < 0 ? -1 : UserID;
    }
}
like image 508
KNgu Avatar asked Apr 17 '15 02:04

KNgu


People also ask

What must DECLARE a scalar variable?

A scalar variable declaration specifies the name and data type of the variable and allocates storage for it. The declaration can also assign an initial value and impose the NOT NULL constraint. You reference a scalar variable by its name.

How do you define a scalar variable?

A scalar variable, or scalar field, is a variable that holds one value at a time. It is a single component that assumes a range of number or string values. A scalar value is associated with every point in a space.

How do you DECLARE a variable in SQL?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


1 Answers

OleDb does not support named parameters. I presume this is what is causing the errors. Instead, within the SQL query, use ? instead of the param name, and ensure the order of parameters added matches the order they appear in the query. so:

using(OleDbCommand cmd = new OleDbCommand("SELECT UserID FROM tblUser WHERE Username=? AND Password = ?", conn))
{
        cmd.Parameters.AddWithValue("@user", user);
        cmd.Parameters.AddWithValue("@pass", pass);

        int UserID = (int)cmd.ExecuteScalar();

        return UserID < 0 ? -1 : UserID;
}
like image 85
Fiddles Avatar answered Sep 28 '22 07:09

Fiddles