我正在制作一个登录表单,每当我尝试登录时(无论是否使用正确的用户),它都会给我同样的错误。
“对象引用未设置为对象的实例”
以下是代码:
Public Class login
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=@p_userid AND PASSWORD=@p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
Dim da As New OleDb.OleDbDataAdapter
Private Sub login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'I figured how to make comments in VB! Yeey
'Temporarely redirecting to menuForm
With cmd
.Parameters.AddWithValue("p_userid", username.Text)
.Parameters.AddWithValue("p_passw", password.Text)
End With
Try
conn.Open()
Dim usr As String = cmd.ExecuteScalar.ToString
If Not (IsDBNull(usr)) AndAlso usr = username.Text Then
Me.DialogResult = Windows.Forms.DialogResult.OK
Else
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End If
Catch ex As Exception
MsgBox("Could not connect to DB hahahaha" & Environment.NewLine & "Error message: " & ex.Message)
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Finally
conn.Close()
Me.Close()
End Try
End Sub
Private Sub closeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeBtn.Click
End
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
credits.Show()
End Sub
End Class
我正在使用Visual Basic Express和Microsoft Access 2010, 谢谢:D
答案 0 :(得分:0)
我看到了几个问题,但我认为问题中提到的问题是:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=@p_userid AND PASSWORD=@p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
问题是这些变量是类级别的,在类构造函数之前初始化,并且不保证变量初始化的顺序。发生的事情是,在New OleDb.OleDbCommand(sql, conn)
代码执行时,conn
变量不能保证已初始化。
这个遗漏将一直在雷达之下,一直到你试图执行一个命令,在这里:
Dim usr As String = cmd.ExecuteScalar.ToString
除了需要函数调用的括号之外,OleDbCommand
对象最终尝试使用前面提供的连接并发现那里有Nothing
,这并不是唯一的。
虽然我引起了您的注意,但我还需要指出您对OleDb使用了错误的参数表示法(您需要使用?
占位符而不是@NameParameters
)。此外,这是一种处理身份验证的可怕方式。 从不以明文形式存储密码。