使用float(C#)汇总sql列

时间:2016-04-07 15:23:22

标签: c# sql

我正在使用此代码:

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'。存在显式转换(您是否错过了演员?)

我错过了什么吗?

2 个答案:

答案 0 :(得分:4)

SqlCommand.ExecuteScalar返回一个对象,您必须将其转换/转换为您需要的类型。如果您希望SUM在数据库中属于float类型,那么在SQL服务器maps中使用double到C {中的float使用double 。像:

double sum = (double) cmd.ExecuteScalar();

另外,请考虑将SqlConnectionSqlCommand对象括起来using statement,以确保资源可以处置,即使发生异常也是如此。

答案 1 :(得分:1)

在总结价格时,如12.3456.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());
  }
}