需要写一个总和(成绩)/总和(学分)代码

时间:2014-06-17 12:41:08

标签: c# mysql sql sum

我正在创建一个学生数据库,其中包含课程ID,课程名称,每门课程的学分,通过失败声明和成绩。 我的目的是让按钮显示总和(成绩)/总和(学分)

这是我讨厌的代码,它给了我一个错误,说明" 已经打开了与此连接关联的数据加载器,必须先关闭 &#34。 有我的代码:

private void button1_Click(object sender, EventArgs e)
        {
           string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
           string Query = " Select sum(grade) from studentdata.semestre1";
           string Query1 = " Select sum(grade) from studentdata.semestre1";
           MySqlConnection ConDatabase = new MySqlConnection(ConString);
           MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
           MySqlCommand cmdDataBase1 = new MySqlCommand(Query1, ConDatabase);

           MySqlDataReader myReader;
           MySqlDataReader myReader1;

            ConDatabase.Open();

            myReader = cmdDataBase.ExecuteReader() ;
            myReader1 = cmdDataBase1.ExecuteReader();

            while ((myReader.Read()) && (myReader1.Read()))
            {
                textBox2.Text =Convert.ToString(double.Parse( myReader.GetString(0))/ double.Parse(myReader1.GetString(0))) ;
            }
            myReader.Close();
            myReader1.Close();
任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

错误表明datareader处于打开状态,其他地方。它是连接对象的类似物。你不必创建两次,你可以在一个查询中做同样的事情

  string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
  string Query = "Select SUM(grade)/SUM(credits) FROM studentdata.semestre1";
  MySqlConnection ConDatabase = new MySqlConnection(ConString);
  MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
  MySqlDataReader myReader;
  ConDatabase.Open();

  while ((myReader.Read()) && (myReader1.Read()))
        {
            textBox2.Text =Convert.ToString(double.Parse( myReader.GetString(0))) ;
        }
  myReader.Close();

答案 1 :(得分:0)

您需要关闭第一个MySqlDataReader以使用相同的连接打开另一个using。我建议您使用MySqlDataReader关键字,因为IDisposable实现了 double grades, credits; string ConString = " datasource = localhost; port = 3306; username = root; password = 3306"; string Query = " Select sum(grade) from studentdata.semestre1"; string Query1 = " Select sum(credit) from studentdata.semestre1"; MySqlConnection ConDatabase = new MySqlConnection(ConString); ConDatabase.Open(); using(MySqlDataReader myReader = cmdDataBase.ExecuteReader()) { grades = double.Parse(myReader.GetString(0)); } using(MySqlDataReader myReader1= cmdDataBase1.ExecuteReader()) { credits = double.Parse(myReader1.GetString(0))) ; } ConDatabase.Close(); textBox2.Text =Convert.ToString(grades/credits).ToString();

{{1}}

答案 2 :(得分:0)

您需要在连接字符串中添加MultipleActiveResultSets = True,才能在同一连接上打开多个数据对象。

http://msdn.microsoft.com/en-us/library/h32h3abf%28v=vs.80%29.aspx