我正在尝试使用产品名称获取产品价格。以下是我正在使用的功能。
public int GetProductPrice(string ProductName)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT ProductPrice FROM Products WHERE ProductName ='" + ProductName + "'", cnn);
int price = (int)cmd.ExecuteScalar();
return price;
}
现在我不断收到此错误Specified cast is not valid
,我不知道为什么。有人可以帮助我吗?
最佳答案
首先,您应该使用参数化SQL,而不是将参数直接放入SQL。此外,您应该在完成后使用 using
语句关闭命令和连接。哦,为每个操作创建一个新的 SqlConnection
。所以像这样:
public int GetProductPrice(string productName)
{
// Quite possibly extract the connection creation into a separate method
// to call here.
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(
"SELECT ProductPrice FROM Products WHERE ProductName = @ProductName",
conn))
{
command.AddParameter("@ProductName", SqlDbType.VarChar)
.Value = productName;
object price = command.ExecuteScalar();
// And you'd do the casting here
}
}
}
接下来,我们不知道 ProductPrice
字段的类型。可能是您返回了一个 long
,或者可能是 decimal
。找出答案的最简单方法就是使用:
object tmp = cmd.ExecuteScalar();
...然后查看调试器。还要查看数据库中字段的类型 - 这应该真正告诉您期望什么。看看 SqlDbType
两者之间映射的枚举。
关于c# - 尝试使用 ExecuteScalar ,并得到 "Specified cast is not valid "错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15577488/