【问题标题】:Error message when trying to connect to an Access database尝试连接到 Access 数据库时出现错误消息
【发布时间】:2017-08-20 03:44:15
【问题描述】:

我在尝试连接到我的 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

任何帮助将不胜感激,因为我不明白为什么会发生此错误。

【问题讨论】:

  • 错误似乎很明显。您应该在尝试运行 ExecuteReader 之前调用 myConnection.Open
  • 完美,谢谢!

标签: database vb.net ms-access


【解决方案1】:

你需要打开连接:

myConnection.Open

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

Using cmd As New OlbDbCommand

【讨论】:

    【解决方案2】:

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

    myConnection.ConnectionString = connString
    myConnection.Open()
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-07-13
        • 2012-06-16
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 2014-03-08
        相关资源
        最近更新 更多