簡體   English   中英

ASP.NET列到字符串的總和

[英]ASP.NET Sum of column to string

我試圖將一列的總和顯示為字符串。 怎么了? 我從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);
            }
        }
    }

您不需要ExecuteReader它通常用於通過讀取器讀取多個返回的記錄。 您需要的是ExecuteScalar例如:

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

請記住將其強制轉換為必需的類型。 由於,應為小數,這似乎是您基於金錢進行計算。

如果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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM