我试图将列的总和显示为字符串。怎么了? 我从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);
}
}
}
答案 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);
}