guetty
guetty

Reputation: 13

Having trouble with the sum function

I am making a student database which contain the course id, course name, credits of each course, pass fail statement and the grades. Now I want to get the sum of the grades in a button and make them appear on a textbox. this is the code I wrote, but it's giving me an error saying the sum function doesn't exist. What should I do?

private void button1_Click(object sender, EventArgs e)
{
   string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
   string Query = " Select sum (grade) form studentdata.semestre1";
   MySqlConnection ConDatabase = new MySqlConnection(ConString);
   MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
   MySqlDataReader myReader;
    ConDatabase.Open();
    myReader = cmdDataBase.ExecuteReader() ;
    while (myReader.Read())
    {
        textBox2.Text = myReader.GetString(0);
    }
    myReader.Close();

Upvotes: 0

Views: 73

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222552

Two reasons:

  1. SQL query should not have space between the function and the column name

  2. Change your query from "Form" to "FROM"

    string Query = "Select SUM(grade) FROM studentdata.semestre1";
    

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062630

Try:

 SELECT SUM(grade) FROM studentdata.semestre1

The most important change is the from.

For a more complete fix; add using, and use ExecuteScalar here:

using(MySqlConnection ConDatabase = new MySqlConnection(ConString))
using(MySqlCommand cmdDataBase = new MySqlCommand(
    "SELECT SUM(grade) FROM studentdata.semestre1", ConDatabase))
{
    ConDatabase.Open();
    textBox2.Text = Convert.ToString(cmdDataBase.ExecuteScalar());
}

Upvotes: 1

Related Questions