尝试使用ExecuteScalar,并获得“指定的强制转换无效”错误

时间:2013-03-22 18:33:14

标签: c# sql winforms

我试图通过使用产品名称来获得产品价格。以下是我正在使用的功能。

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,我不知道为什么。有人能帮助我吗?

1 个答案:

答案 0 :(得分:11)

首先,您应该使用参数化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枚举。

相关问题