请帮我做作业。由于这个错误,我无法完成
已经有与此命令关联的打开的DataReader,必须先关闭
这是我的代码:
con.Open()
Dim rs As New MySqlCommand("select * from account where username='" & txtu.Text & "' and password='" & txtp.Text & "' ", con)
Dim sqlRead As MySqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("level") = "admin" Then
MessageBox.Show("Can't Delete.")
ElseIf sqlRead("level") = "staff" Then
Dim query As String = "delete from account where username='" & txtu.Text & "'"
Dim cmd As New MySqlCommand(query, con)
cmd.ExecuteNonQuery()
sqlRead.Close()
End If
End If
End If
End If
con.Close()
答案 0 :(得分:0)
要以您尝试的方式进行操作,您还需要创建一个新连接以与new命令一起使用,在这种情况下,您将导致可避免的连接。
Private Sub DReader()
Using Con As New MySql.Data.MySqlClient.MySqlConnection("ConnectionString")
Con.Open()
Using MySqlReader As MySql.Data.MySqlClient.MySqlDataReader =
New MySql.Data.MySqlClient.MySqlCommand("Command", Con).ExecuteReader
While MySqlReader.Read
Select Case MySqlReader.GetString(MySqlReader.GetOrdinal("level")).ToUpper
Case "ADMIN"
MessageBox.Show("Can't Delete.")
Case "STAFF"
Dim query As String = "delete from account where username='" & txtu.Text & "'"
DelRow(query)
End Select
End While
End Using
Con.Close()
End Using
End Sub
Private Sub DelRow(ByVal Qry As String)
Using Con As New MySql.Data.MySqlClient.MySqlConnection("ConnectionString")
Con.Open()
Using DelCmd As New MySql.Data.MySqlClient.MySqlCommand(Qry, Con)
DelCmd.ExecuteNonQuery()
End Using
Con.Close()
End Using
End Sub
我相信这可以回答您的问题,但是,您确实应该问如何实现此例程执行的目标。参数和“ ExecuteScalar”将是更好的做法
答案 1 :(得分:0)
我认为您只需要放置以下代码: sqlRead.Close() 在最后一个if之后,因为当此“内部if”代码正确时,将有很大的机会运行代码: 如果sqlRead(“ level”)=“ admin”然后 还需要关闭。
简而言之,只有执行以下代码,您的阅读器才会关闭: ElseIf sqlRead(“ level”)=“ staff”然后
因此,将其更新为:
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("level") = "admin" Then
MessageBox.Show("Can't Delete.")
ElseIf sqlRead("level") = "staff" Then
Dim query As String = "delete from account where username='" & txtu.Text & "'"
Dim cmd As New MySqlCommand(query, con)
cmd.ExecuteNonQuery()
End If
End If
End If
End If
sqlRead.Close()
con.Close()
希望这对大家有帮助,