0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That worked! The table in my DB is set to INT, but removing the cast worked fine :) But it will contain money in the future, so you taught me something useful :)
@BPW, You are welcome, Just to add, with int you can't store decimal points in your table. It would depend on your requirements, but generally for money the data type used should be decimal.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.