计算Windows窗体应用程序的mysql数据库中列的平均值

时间:2013-11-14 20:41:08

标签: c# mysql windows forms

我正在尝试计算我的mysql数据库列的平均值并将其保存在变量中,以便我可以将其用于进一步计算,例如查找正态分布的方差。但是,当我运行我的代码时,它并没有向我显示任何错误,但它也没有读取数据库。我在代码中添加了检查点,以了解它的进展情况。程序在检查点2之前显示异常消息“没有数据库选择”。任何帮助将不胜感激。

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

2 个答案:

答案 0 :(得分:1)

您没有在ConnectionString对象中指定数据库名称。

试试这个:

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

MySQL Connection String

推荐此链接

答案 1 :(得分:0)

您的代码存在一些问题,我将在答案中突出显示它们。

decimal proteinAvg;
// MySql uses 'database' and not 'Initial Catalog' like Sql does.
string myConnection = string myConnection = "datasource=localhost;Database=mydatabase;port=3306;username=root;password=root";  // MySql uses 'database' to define the DB name.
string Query = "SELECT AVG(Protein) AS proteinAvg FROM nutritioncalculator";

// Wrap your connection and command objects in 'using' blocks.  
// Both implement IDisposable and will be managed by GC once 
// they fall out-of-scope. 
using (MySqlConnection myConn = new MySqlConnection(myConnection))
{   
   using (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);
         }
      }
   }
}