我不断收到这个恼人的错误。我对 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/