calculating average of a column in mysql database for windows form application Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of calculating average of a column in mysql database for windows form application without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to compute average of a column of my mysql database and save it in a variable so I can use it for further calculation such as finding variance for normal distribution. How ever, when I run my code, it’s not showing me any error but it’s not reading database either. I have added checkpoints in my code to see how far it is going. Program is showing me exception message “No database selected” before checkpoint 2. Any help would be appreciated.

decimal proteinAvg;

        string myConnection = "datasource=localhost;port=3306;username=root;password=root"
        string Query = "SELECT AVG(Protein) AS proteinAvg FROM nutritioncalculator";
        MySqlConnection myConn = new MySqlConnection(myConnection);
        MySqlCommand cmdDatabase = new MySqlCommand(Query, myConn);
        MySqlDataReader myReader;


try
{
   myConn.Open();
   //checkpoint1
   MessageBox.Show("connected");
   myReader = cmdDatabase.ExecuteReader();
   //Checkpoint2

   MessageBox.Show("connected");
   while (myReader.Read())
   {
      //checkpoint3
      MessageBox.Show("connected");
      proteinAvg = (decimal) myReader["proteinAvg"];
      MessageBox.Show("Your protein intake should be around" + proteinAvg);
   }

Answer

You are not specifying a database name in your ConnectionString object.

Try this:

string myConnection = "datasource=localhost;Database=mydatabase;port=3306;username=root;password=root";

Refere this Link for MySQL Connection String

We are here to answer your question about calculating average of a column in mysql database for windows form application - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji