尝试连接到Access数据库时出现错误消息

时间:2017-03-27 12:21:52

标签: database vb.net ms-access

尝试连接到Access数据库时收到以下错误消息:

  

System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常

     

其他信息:ExecuteReader需要一个开放且可用的连接。连接的当前状态已关闭。

以下是我的表单的代码:

Imports System.Data.OleDb

Public Class Login

Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection

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

    provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    'Change the following to your access database location
    dataFile = "C:\Users\115520963\Documents\users.accdb"
    connString = provider & dataFile
    myConnection.ConnectionString = connString

    'the query:
    Dim cmd As OleDbCommand = New OleDbCommand("'SELECT * FROM [users] WHERE [username] = '" & txtUsername.Text & "' AND [password] = '" & txtPassword.Text & "'", myConnection)
    Dim dr As OleDbDataReader = cmd.ExecuteReader
    ' the following variable is hold true if user is found, and false if user is not found
    Dim userFound As Boolean = False
    ' the following variables will hold the user first and last name if found.
    Dim FirstName As String = ""
    Dim LastName As String = ""

    'if found:
    While dr.Read
        userFound = True
        FirstName = dr("FirstName").ToString
        LastName = dr("LastName").ToString
    End While

    'checking the result
    If userFound = True Then
        Secondary.Show()
        Secondary.lblWelcome.Text = "Welcome " & FirstName & " " & LastName
    Else
        MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
    End If

End Sub



End Class

错误发生在该行:

Dim dr As OleDbDataReader = cmd.ExecuteReader

任何帮助都会非常感激,因为我不明白为什么会出现这种错误。

3 个答案:

答案 0 :(得分:4)

您需要打开连接:

myConnection.Open

您可能还希望将代码包装在Using语句中:

Using cmd As New OlbDbCommand

答案 1 :(得分:1)

异常消息告诉您需要打开连接,请尝试:

myConnection.ConnectionString = connString
myConnection.Open()

答案 2 :(得分:0)

完成后不要忘记myConnection.close。理想情况下,您应该尽快打开并尽快关闭。