连接未关闭(vb)

时间:2016-03-12 09:32:48

标签: vb.net ms-access connection

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click

    Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")

    txtAdmin.Text = "Admin"

    Dim strsql As New OleDbCommand("select * from Account where Username ='" & txtUsername.Text & "' AND [Password] ='" & txtPassword.Text & "' AND AccountType = '" & txtAdmin.Text & "'", conn)
    Dim strsql2 As New OleDbCommand("select * from Account where Username ='" & txtUsername.Text & "' AND [Password] ='" & txtPassword.Text & "' AND AccountType = '" & txtStudent.Text & "'", conn)
    Dim uu As New OleDbParameter("UserName", txtUsername.Text)
    Dim pp As New OleDbParameter("Password", txtPassword.Text)
    strsql.Connection.Open()
    strsql2.Connection.Open()


    Dim reader As OleDbDataReader
    reader = strsql.ExecuteReader

    Dim reader2 As OleDbDataReader
    reader2 = strsql2.ExecuteReader

    If reader.HasRows Then
        strsql.Connection.Close()

        MsgBox(" Welcome Admin!", vbInformation)

        frmIndex.Show()
        desktopFade.Close()

    ElseIf reader2.HasRows Then
        strsql2.Connection.Close()

        MsgBox(" Welcome Student!", vbInformation)

        frmReg.Show()
        desktopFade.Close()

    ElseIf txtUsername.Text = "" And txtPassword.Text = "" Then
        MsgBox("Don't leave the fields blank", vbCritical)
        txtUsername.Focus()

    Else

        MsgBox("Your Username or Password is invalid", MsgBoxStyle.Critical)
        Me.txtUsername.Text = ""
        Me.txtPassword.Text = ""
        Me.txtUsername.Focus()
        strsql.Connection.Close()
        strsql2.Connection.Close()

    End If

此处的错误是strsql2.connection.open()< ---它表示连接未关闭。仍然开放。

1 个答案:

答案 0 :(得分:0)

我编辑了你的问题,因为你把它标记为VBA,这是VB.NET

您的代码有几个问题。 您应该使用Try Catch添加错误捕获,并且您的连接也不会始终关闭

要仅解决实际问题,请在尝试打开连接之前测试连接是否已打开

        If strsql2.Connection.State = ConnectionState.Open Then
            Console.WriteLine("COnnection already open, closing it")
            strsql2.Connection.Close()
        End If
        strsql2.Connection.Open()