ASP.NET要求字符串的总和

时间:2016-04-19 15:41:27

标签: c# sql asp.net

我试图将列的总和显示为字符串。怎么了? 我从cmd.ExecuteReader()得到的唯一输出;似乎是:System.Data.OleDb.OleDbDataReader

       protected void TotalHours() {
        DatabaseConnection.Commandstring = ("SELECT SUM ([Time]) FROM tbl_login");
        using (OleDbConnection con = new OleDbConnection(DatabaseConnection.ConString)) {
            try {
                con.Open();
                using (OleDbCommand cmd = new OleDbCommand(DatabaseConnection.Commandstring, con)) {
                    DatabaseConnection.result = cmd.ExecuteReader();
                    txt_TotalTime.Text = ("Total Time: " + DatabaseConnection.result.ToString());
                    con.Close();
                }
            }

            catch (Exception ex) {
                con.Close();
                Debug.WriteLine("Error Selecting Time from Database " + ex.Message);
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

您不需要ExecuteReader它通常用于通过阅读器读取多个返回的记录。你需要的是ExecuteScalar喜欢:

  DatabaseConnection.result = (decimal) cmd.ExecuteScalar();

请记住将其强制转换为所需类型。它应该是小数,因为它看起来像是在做基于金钱的计算。

答案 1 :(得分:0)

如果ypu想要使用reader,您必须阅读reader.Read();不要忘记处理读者(将其放入using):

try {
  using (OleDbConnection con = new OleDbConnection(DatabaseConnection.ConString)) {
    con.Open();

    using (OleDbCommand cmd = new OleDbCommand(DatabaseConnection.Commandstring, con)) {
      using (var reader = cmd.ExecuteReader()) {
        if (reader.Read()) // you have to read
          txt_TotalTime.Text = String.Format("Total Time: ", reader.GetValue(0));
      }
    }
  }
}
catch (DbException ex) { // Bad style: do not catch ALL the exceptions
  Debug.WriteLine("Error Selecting Time from Database " + ex.Message);
}