1

我正在尝试计算我的 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);
   }
4

2 回答 2

1

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

尝试这个:

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

请参阅此链接以获取MySQL 连接字符串

于 2013-11-14T20:43:25.413 回答
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);
         }
      }
   }
}
于 2013-11-14T20:51:11.780 回答