ASP.NET列与字符串之和
本文关键字:字符串 NET ASP | 更新日期: 2024-10-21 09:02:49
我试图将列的和显示为字符串。怎么了?我从cmd得到的唯一输出。ExecuteRead();似乎是:系统。数据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);
}