我正在使用此代码:
SqlConnection con = new SqlConnection(@"Data Source=(local);Initial
Catalog=dbsoft;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT SUM(price) FROM fiscal");
cmd.Connection = con;
int sum = cmd.ExecuteScalar();
label3.Text = sum.ToString();
con.Close();
我收到此错误消息:
无法将类型'object'隐式转换为'int'。存在显式转换(您是否错过了演员?)
我错过了什么吗?
答案 0 :(得分:4)
SqlCommand.ExecuteScalar
返回一个对象,您必须将其转换/转换为您需要的类型。如果您希望SUM
在数据库中属于float
类型,那么在SQL服务器maps中使用double
到C {中的float
使用double
。像:
double sum = (double) cmd.ExecuteScalar();
另外,请考虑将SqlConnection
和SqlCommand
对象括起来using
statement,以确保资源可以处置,即使发生异常也是如此。
答案 1 :(得分:1)
在总结价格时,如12.34
,56.78
等,我们可能会获得浮点值。如果是 money ,Decimal
是典型的选择(而不是int
):
...
// Convert.ToDecimal - let .Net convert, not just cast;
// what if, say, String has been returned?
Decimal sum = Convert.ToDecimal(cmd.ExecuteScalar()); // Decimal sum
label3.Text = sum.ToString();
实现:
String connString = @"Data Source=(local);Initial
Catalog=dbsoft;Integrated Security=True";
// Wrap IDisposable into using
using (SqlConnection con = new SqlConnection(connString)) {
con.Open();
// Wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(
@"SELECT SUM(price)
FROM fiscal")) {
cmd.Connection = con;
Decimal sum = Convert.ToDecimal(cmd.ExecuteScalar()); // Decimal sum
label3.Text = sum.ToString();
// or
// Shortcut - you have no need in additional convert/cast
//label3.Text = Convert.ToString(cmd.ExecuteScalar());
}
}