【发布时间】: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
-
完美,谢谢!