2015-03-15 2 views
2

Я искал решение этой проблемы на форуме, но я не нашел ее для своей проблемы. На кнопку мыши, я получаю сообщение об ошибке:Ошибка C# DataReader

There is already an open DataReader associated with this Connection which must be closed first.

Итак, я попытался закрыть все DataReaders после их использования, я попытался использовать CommandBehavior, но ни один из них не работал. Я пытался использовать using(MysqlCommand...), но не работал. Что я могу сделать? Самое странное, что код работает, но после каждой кнопки нажмите, я снова получаю эту ошибку. Есть идеи?

Пожалуйста, не помещайте вопрос как дубликат, я знаю, что вопрос существует здесь, но ответ отсутствует для моей проблемы, я думаю.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using MySql.Data.MySqlClient; 
using System.Drawing.Text; 

namespace simulator 
{ 
    public partial class Simulare : Form 
    { 
     public int corect = 0, incorect = 0; 
     Timer timer; 
     static string dataA = "SELECT DISTINCT * FROM questions order by rand() limit 1"; 
     public int r1; 
     public int r2; 
     public int r3; 
     public Simulare() 
     { 
      InitializeComponent(); 
      this.FormClosing += Form1_FormClosing; 
      label1.Text = TimeSpan.FromMinutes(30).ToString("mm\\:ss"); 
      label10.Text = corect.ToString(); 
      label12.Text = incorect.ToString(); 
      //FormBorderStyle = FormBorderStyle.None; 
      WindowState = FormWindowState.Maximized; 
     } 
     private void simulare_Load(object sender, EventArgs e) 
     { 
      var startTime = DateTime.Now; 
      timer = new Timer() { Interval = 1000 }; 
      timer.Tick += (obj, args) => 
      { 
       TimeSpan ts = TimeSpan.FromMinutes(30) - (DateTime.Now - startTime); 
       label1.Text = ts.ToString("mm\\:ss"); 
       if (ts.Minutes == 00 && ts.Seconds == 00) 
       { 
        timer.Stop(); 
        MessageBox.Show("Timpul a expirat. Ai picat!"); 
        MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()); 
         try 
         { 
          MySqlDataReader upad = upd.ExecuteReader(); 
           while (upad.Read()) 
           { 
            int totalnu = (int)upad["totalno"]; 
            totalnu++; 
            using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET [email protected] where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection())) 
            { 
             update.Parameters.AddWithValue("@totalnu", totalnu); 
             int rows = update.ExecuteNonQuery(); 
            } 
           } 
           upad.Close(); 
         } 
         catch (Exception ex2) 
         { 
          MessageBox.Show(ex2.Message); 
         } 
        } 
      }; 
      timer.Start(); 
      select(); 
     } 

     private void select() 
     { 
      using (ConnConfig.getConnection()) 
      { 
       MySqlCommand cmd = new MySqlCommand(dataA, ConnConfig.getConnection()); 
       cmd.CommandType = CommandType.Text; 
       MySqlDataReader rdra = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
       try 
       { 
        while (rdra.Read()) 
        { 
         label2.Text = rdra["question"].ToString(); 
         label3.Text = rdra["answer1"].ToString(); 
         label4.Text = rdra["answer2"].ToString(); 
         label5.Text = rdra["answer3"].ToString(); 
         r1 = (int)rdra["option1"]; 
         r2 = (int)rdra["option2"]; 
         r3 = (int)rdra["option3"]; 
        } 
        rdra.Close(); 
       } 
       catch (InvalidOperationException ex) 
       { 
        MessageBox.Show(ex.Message); 
       } 
       finally 
       { 
        ConnConfig.closeConn(); 
       } 
      } 
     } 
     private void button1_Click(object sender, EventArgs e) 
     { 
      int result1 = checkBox1.CheckState == CheckState.Checked ? 1 : 0; 
      int result2 = checkBox2.CheckState == CheckState.Checked ? 1 : 0; 
      int result3 = checkBox3.CheckState == CheckState.Checked ? 1 : 0; 
      using(ConnConfig.getConnection()) 
      { 
       MySqlCommand cmd = new MySqlCommand(dataA, ConnConfig.getConnection()); 
       cmd.CommandType = CommandType.Text; 
       MySqlDataReader rdr = cmd.ExecuteReader(); 
       try 
       { 
        while (rdr.Read()) 
        { 
         if (checkBox1.Checked == false && checkBox2.Checked == false && checkBox3.Checked == false) 
         { 
          MessageBox.Show("Bifati minim o casuta!"); 
          return; 
         } 
         else 
         { 
          if ((result1 == r1) && (result2 == r2) && (result3 == r3)) 
          { 
           corect++; 
           label10.Text = corect.ToString(); 
           checkBox1.Checked = false; 
           checkBox2.Checked = false; 
           checkBox3.Checked = false; 
           select(); 
          } 
          else 
          { 
           incorect++; 
           label12.Text = incorect.ToString(); 
           checkBox1.Checked = false; 
           checkBox2.Checked = false; 
           checkBox3.Checked = false; 
           select(); 
          } 
          if (corect + incorect == 26) 
          { 
           int totalalll; 
           timer.Stop(); 
           button1.Enabled = false; 
           MySqlCommand upd = new MySqlCommand("select * from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()); 
           MySqlDataReader upad = upd.ExecuteReader(); 
           while (upad.Read()) 
           { 
            totalalll = (int)upad["totalall"]; 
            totalalll++; 
            using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET [email protected] where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection())) 
            { 
             update.Parameters.AddWithValue("@totalalll", totalalll); 
             Int32 rows = update.ExecuteNonQuery(); 
            } 
           } 
           upad.Close(); 
          } 
          if (corect == 26) 
          { 
           MySqlCommand upd = new MySqlCommand("select totalyes from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()); 
           MySqlDataReader upad = upd.ExecuteReader(); 
           while (upad.Read()) 
           { 
            int totalda = (Int32)upad["totalyes"]; 
            totalda++; 
            using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET [email protected] where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection())) 
            { 
             update.Parameters.AddWithValue("@totalda", totalda); 
             int rows = update.ExecuteNonQuery(); 
            } 
           } 
           upad.Close(); 
           MessageBox.Show("Bravos"); 
          } 
          else 
          { 
           MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()); 
           MySqlDataReader upad = upd.ExecuteReader(); 
           while (upad.Read()) 
           { 
            int totalnu = (int)upad["totalno"]; 
            totalnu++; 
            using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET [email protected] where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection())) 
            { 
             update.Parameters.AddWithValue("@totalnu", totalnu); 
             int rows = update.ExecuteNonQuery(); 
            } 
           } 
           upad.Close(); 
           MessageBox.Show("Mai invata!"); 
          } 
         } 
        } 
        rdr.Close(); 
       } 
       catch (MySqlException ex) 
       { 
        MessageBox.Show(ex.Message); 
       } 
       finally 
       { 
        ConnConfig.closeConn(); 
       } 
      } 
     } 

     private void Form1_FormClosing(Object sender, FormClosingEventArgs e) 
     { 
      if (e.CloseReason == CloseReason.WindowsShutDown) return; 

      if (this.DialogResult == DialogResult.Cancel) 
      { 
       e.Cancel = false; 
       timer.Stop(); 
      } 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      this.Close(); 
     } 
    } 
} 

class ConnConfig 
    { 
     private static string conn = "string connection"; 
     public static MySqlConnection connect; 

     private ConnConfig() 
     { 

     } 
     public static MySqlConnection getConnection() 
     { 
      if(connect !=null){ 

       return connect; 
      } 
      else 
       try{ 
        connect = new MySqlConnection(conn); 
        connect.Open(); 
        return connect; 
       } 
      catch(MySqlException e){ 
       throw new Exception("Cannot connect",e); 
      } 
     } 
     public static void closeConn() 
     { 
      connect.Close(); 
     } 
     public static void openConn() 
     { 
      connect.Open(); 
     } 
    } 
+1

Парень, который просто «-1 «Если вы умны, можете ли вы дать мне решение? – dpaul1994

+1

Какая именно строка, в которой выбрано исключение? – bokibeg

+1

Для записи это не я, кто вас ниспровергал: P. – bokibeg

ответ

1

изменить функцию GetConnection

public static MySqlConnection getConnection() 
    { 
     MySqlConnection connect = null; 
     try 
     { 
      connect = new MySqlConnection(connect); 
      connect.Open(); 
      return connect; 
     } 
     catch (MySqlException e) 
     { 
      throw new Exception("Cannot connect", e); 
     } 
    } 

пусть все остальные коды, как это

+0

Теперь я получаю: 'Дополнительная информация: Ссылка на объект не установлена ​​в экземпляр object.', и ошибка появляется, когда я пытаюсь открыть форму – dpaul1994

+0

i; ve отредактирован .... – Sayka

+0

По той же ошибке, что и раньше – dpaul1994

1

Основная причина вашего исключения заключается в том, что вы выполняете другие запросы, в то время как вы все еще итерацию по результатам более раннего запроса. В нижней строке вы не должны вставлять такие запросы, как вы, если используете одно и то же соединение для вложенных запросов.

1

Вы используете считыватель для извлечения данных из обновления SQLCommand.

Затем вы читаете значение.

После того, что вы используете другой SQLCommand «обновление», чтобы обновить результат ..

Даже при использовании двух различных SQLCommands, вы используете соединение. Это проблема. Используйте второе соединение для второго SQLCommand, и ваша проблема будет решена.

Попробуйте это.

после строки

MessageBox.Show("Timpul a expirat. Ai picat!"); 

добавить как

MessageBox.Show("Timpul a expirat. Ai picat!"); 
MySqlConnection conn1 = ConnConfig.getConnection(); 
MySqlConnection conn2 = new MySqlConnection(); 
conn2.ConnectionString = conn1.ConnectionString; 
conn2.Open(); 

, а затем в строке

MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()); 

изменения как

MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", conn1); 

и в соответствии

using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET [email protected] where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection())) 

изменение как

using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET [email protected] where username = '" + Index.textBox1.Text + "'", conn2)) 
+0

Я понимаю, но в моей ситуации. где я должен закрыть и снова открыть соединение? Потому что у меня есть MysqlCommand в другом MysqlCommand – dpaul1994

+0

, который я редактировал. Попробуйте и проголосуйте, если он работает – Sayka

+0

Конечно, я проголосую, если он сработает. Я проверю это сейчас! – dpaul1994