2013-02-05 37 views
0

關閉我也遇到過這樣的問題:個MySqlException是與此相關的未處理的DataReader必須vb.net

錯誤:已經有與此連接必須先關閉相關聯的打開的DataReader。

請對我的代碼來看看:

Dim sqlQuery As String = "SELECT * FROM users" 
    Dim myAdapter As New MySqlDataAdapter 

    If txtUsername.Text = String.Empty And txtPassword.Text = String.Empty Then 
     MsgBox("Enter username and password", MsgBoxStyle.Exclamation, "Tea Sparkle POS") 
    Else 
     Dim sqlquerry = "Select * From users where username = '" + txtUsername.Text + "' And password= '" + txtPassword.Text + "'" 
     Dim myCommand As New MySqlCommand() 
     myCommand.Connection = SQLConnection 
     myCommand.CommandText = sqlquerry 
     'Starting The Query 
     myAdapter.SelectCommand = myCommand 
     Dim mydata As MySqlDataReader 
     mydata = myCommand.ExecuteReader() 
     'To check the Username and password and to validate the login a 
     If mydata.HasRows = 0 Then 
      MsgBox("Invalid Login") 
      txtPassword.Clear() 
      txtUsername.Clear() 
     Else 
      Dim authorityid = 0 
      While mydata.Read() 
       authorityid = mydata.GetInt32("authorityid") 
      End While 
      MsgBox("Welcome " + txtUsername.Text + "!") 
      If authorityid = 1 Then 
       MainForm.Show() 
      Else 
       MainForm.Show() 
      End If 
      Me.Hide() 
     End If 
    End If 


    Private Sub Login_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 

    SQLConnection.ConnectionString = ServerString 

    Try 
     If SQLConnection.State = ConnectionState.Closed Then 
      SQLConnection.Open() 
     Else 
      SQLConnection.Close() 
     End If 
    Catch ex As Exception 
     MsgBox(ex.ToString) 
    End Try 

End Sub 

此錯誤是在這一行:

mydata = myCommand.ExecuteReader() 

這有什麼錯呢?任何幫助是真正的讚賞。

+0

您需要使用'try/catch'塊併發布'exception'消息。 – Brian

+0

@Brian我更新了我的代碼。我忘了把什麼放在我的表格加載 –

回答

2

What's wrong with this?

嗯,它看起來像你重用現有的連接:

myCommand.Connection = SQLConnection 

不要那樣做。每次需要與數據庫交談時創建一個新連接,並在完成後關閉它,使用Using語句確保即使拋出異常也會關閉它。

另外,爲您的命令使用Using語句,爲讀者使用另一個語句 - 這些都是您應該關閉的所有資源。

噢,它也看起來像你在UI線程中這樣做,這是一個壞主意,因爲當數據庫訪問正在進行時,你的UI將不響應。

+0

你好,你能給我一些例子誰使用使用語句?謝謝。 –

+0

'使用(SqlCommand sqlCommand = new SqlCommand()){}'是Jon正在談論的內容。 – Brian

+0

@布萊恩我覺得這是爲C#? –

相關問題