Vb.net 连接未关闭(vb)

Vb.net 连接未关闭(vb),vb.net,ms-access,connection,Vb.net,Ms Access,Connection,这里的错误是strsql2.connection.open() 您的代码有几个问题。 您应该使用Try Catch添加错误捕获,而且您的连接并不总是关闭的 要仅修复实际问题,请在尝试打开连接之前测试连接是否已打开 Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click Dim conn As New OleDbConnect

这里的错误是strsql2.connection.open()

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

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

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

这可以通过为2命令对象使用第二个连接对象轻松解决。重复使用连接对象总是会导致问题。a)许多数据库提供程序对象应该被处理掉b)总是使用SQL参数而不是concat SQL。请尝试使用
D'Artagnan
用户名,了解为什么c)从不将密码存储为明文,对其进行散列,D)从不使用默认表单实例。
        If strsql2.Connection.State = ConnectionState.Open Then
            Console.WriteLine("COnnection already open, closing it")
            strsql2.Connection.Close()
        End If
        strsql2.Connection.Open()