刚接触 C# 并使用 Windows 窗体应用程序。我正在尝试对 SQL 数据库执行更新查询,但一直遇到“必须声明标量变量”错误,我不明白为什么。
以下代码成功打开连接。我的更新声明是有效的。浏览了很多关于这个主题的帖子,我只是没有看到我的错误......任何帮助将不胜感激。
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = @stationId AND ID <> @jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//below AddWithValue gives error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@stationId".'
//command.Parameters.AddWithValue("@stationId", 1);
//command.Parameters.AddWithValue("@jobId", JobId);
//next I tried this, and the same error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@stationId".'
command.Parameters.Add("@stationId", SqlDbType.Int);
command.Parameters["@stationId"].Value = 1;
command.Parameters.Add("@jobId", SqlDbType.Int);
command.Parameters["@jobId"].Value = JobId;
adapter.UpdateCommand = new SqlCommand(strSql, conn);
adapter.UpdateCommand.ExecuteNonQuery();
}
}