我想通过使用参数化方法获取值,但我收到此错误“必须声明标量变量@Category”。我不知道在下面的代码中在哪里以及如何声明标量变量。
查看我尝试过的代码
` [Route("TotalValue")]
[HttpGet]
public decimal TotalValue()
{
var query = "Select * from OrderDetail where Category = @Category";
string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");
decimal total = 0;
using (SqlConnection con = new SqlConnection(sqlDataSource))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
total = dr.GetDecimal(0);
}
}
}
con.Close();
}
return total;
}`
你就快到了。
创建命令后,将@Category参数添加到命令的参数集合中:
[Route("TotalValue")]
[HttpGet]
public decimal TotalValue()
{
var query = "Select * from OrderDetail where Category = @Category";
string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");
decimal total = 0;
// If a string (amend for other data type)
string categoryToFind = "My Category To Search For";
using (SqlConnection con = new SqlConnection(sqlDataSource))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@Category", categoryToFind);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
total = dr.GetDecimal(0);
}
}
}
con.Close();
}
return total;
}