c# - 如何通过C#修复SQL查询中的错误 'Must declare scalar variable'?

标签 c# sql-server

我不断收到这个恼人的错误。我对 SQL 真的很陌生,这实际上是我的第一个查询,但我就是无法让它工作。我已经尝试了几个小时了。请帮忙!

我收到错误:

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@FirstNamez".

代码:

public static void CreateNewEmployee(string FirstNamez, string LastNamez, int Pinz, string Departmentz)
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = @"Server = localhost\SQLEXPRESS; Database = Employee; Trusted_Connection = True;";

    SqlCommand command = new SqlCommand();

    using (connection)
    {
        connection.Open();
        string commandtext = "INSERT INTO dbo.EmployeeDatabase (FirstName, LastName, PIN, Department) VALUES (@FirstNamez, @Lastnamez, @Pinz, @Departmentz);";

        command.CommandText = commandtext;
        command.Connection = connection;

        command.ExecuteNonQuery();
    }
}

最佳答案

您在查询文本中定义所有参数 - 但您从未设置它们的值!

试试这个:

public static void CreateNewEmployee(string FirstNamez, string LastNamez, int Pinz, string Departmentz)
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = @"Server = localhost\SQLEXPRESS; Database = Employee; Trusted_Connection = True;";

    SqlCommand command = new SqlCommand();

    using (connection)
    {
        connection.Open();
        string commandtext = "INSERT INTO dbo.EmployeeDatabase (FirstName, LastName, PIN, Department) VALUES (@FirstNamez, @Lastnamez, @Pinz, @Departmentz);";

        command.CommandText = commandtext;
        command.Connection = connection;

        // define the parameters and set their values!
        command.Parameters.Add("@FirstNamez", SqlDbType.VarChar, 100).Value = FirstNamez;
        command.Parameters.Add("@LastNamez", SqlDbType.VarChar, 100).Value = LastNamez;
        command.Parameters.Add("@Pinz", SqlDbType.Int).Value = Pinz;
        command.Parameters.Add("@Departmentz", SqlDbType.VarChar, 100).Value = Departmentz;

        command.ExecuteNonQuery();
    }
}

关于c# - 如何通过C#修复SQL查询中的错误 'Must declare scalar variable'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51034880/

相关文章:

c# - 从 .NET 调用 SQL Server 2008 中的存储过程时结果未正确排序

c# - 如何使用泛型类型参数获取类的所有属性

c# - 编辑Word书签更改字体

sql-server - SQL Server 日期格式 yyyymmdd

SQL Server : auto-generate records in a range with filtering?

c# - 使用 C# 通过 cmd.exe 运行多个命令

c# - 如何在MemoryStream中显示图像?

sql-server - 通过 unixODBC 和 FreeTDS 从 MSSQL 返回西里尔符号的问题

SQL Server 2008日志不会截断

sql - JOIN 和 INNER JOIN 之间的区别