Reputation: 17
I'm trying to show the sum of a column as a string. What's wrong? The only output I get from cmd.ExecuteReader(); seems to be: 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);
}
}
}
Upvotes: 0
Views: 92
Reputation: 186843
If ypu want to use reader
you have to read: reader.Read()
; do not forget to dispose reader as well (put it into 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);
}
Upvotes: 0
Reputation: 223422
You don't need ExecuteReader
it is usually used to read multiple returned records through a reader. What you need is ExecuteScalar
like:
DatabaseConnection.result = (decimal) cmd.ExecuteScalar();
Remember to cast it to required type. It should be decimal since , it looks like you are doing caculation based on money.
Upvotes: 1