Home > Software design >  C# using SQL, error: Must declare the scalar value @name
C# using SQL, error: Must declare the scalar value @name

Time:02-27

Im new to c# and for this I´m supposed to ask for a new name and description for a category and add that to the already existent table, but im having problems with the declaring scalar value as im not sure how to do that.

This i where i ask the values

Console.WriteLine("Category Name? \n");
n= Console.ReadLine();
Console.WriteLine("New description? \n");
d = Console.ReadLine();

And here is where the sql query begins

var sql = new SqlCommand("INSERT INTO Categories (CategoryName, Description) "    
                                 "VALUES (@name, @description", cn)

        SqlParameter name = new SqlParameter();
        name.ParameterName = "@name";
        name.Value = n;

        SqlParameter description = new SqlParameter();
        name.ParameterName = "@description";
        name.Value = d;

        sql.Parameters.Add(name);
        sql.Parameters.Add(description);

The code does ask me to write the name and description in the cmd the error comes after entering the new values. My question is how do i fix the declare scalar value error? Am i not declaring it in here?

    name.ParameterName = "@name";
    name.Value = n;

CodePudding user response:

It looks like you have a simple copy/paste fail, you're replacing the @name parameter with @description

SqlParameter name = new SqlParameter();
name.ParameterName = "@name";
name.Value = n;

SqlParameter description = new SqlParameter();
description.ParameterName = "@description";
description.Value = d;

CodePudding user response:

You have made a simple copy/paste error, as mentioned.

The easiest and most concise way to add properly parameters is to use the constructor of SqlParameter or to use Parameters.Add

const string query = @"
INSERT INTO Categories (CategoryName, Description)
VALUES (@name, @description";
using (var sql = new SqlCommand(query, cn))
{
    sql.Parameters.Add("@name", SqlDbType.VarChar, 100).Value = n;
    sql.Parameters.Add("@description", SqlDbType.VarChar, 100).Value = d;

    sql.ExecuteNonQuery();  // or whatever
}

Note the use of the following best practices:

  • using block for SqlCommand (the same goes for SqlConnection and SqlDataReader)
  • A multi-line verbatim string for the actual query batch, which makes it easier to read.
  • Specify the parameter types and lengths explicitly. This improves performance with regards to implicit conversions and query plan caching.

CodePudding user response:

var sql = new SqlCommand("INSERT INTO Categories (CategoryName, Description) "    
                             "VALUES (@name, @description", cn)

Here your are trying to insert two values and providing 3. This is where you may be getting Error and ofcourse do check out above answers too.

  • Related