当我运行代码时,我收到一条错误消息:对象引用未设置为对象的实例。我想创建一个代码来验证数据库中的凭据。如果用户未输入有效信息,则会显示错误消息。这是我的代码:
'Declare variables
Dim pwd, username As String
Dim dbpwd, dbUsername As String
'Get credentials variables
username = Me.username.Text
pwd = Me.TextBox2.Text
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim sqlConn As String
If username <> "" And pwd <> "" Then
objConn = New MySqlConnection("server=localhost;userid=root;password= ;database=mayombe_mdcs")
objConn.Open()
sqlConn = "select agent_id, Password from password where agent_id = " & username & ""
Try
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset)
' intRowNumber = sqlR
dbUsername = objDataset.Tables("password").Rows(1).Item(2)
' dbpwd = objDataset.Tables("password").Rows(1).Item(1)
'WriteLine (dbUsername )
'Force users to enter credentiasl
objConn.Close()
'Force user to enter true credentials
If pwd = dbpwd And username = dbUsername Then
open form
Me.Close()
End If
Catch ex As Exception
strMsg As String
Prompt message that tells the user that credentials entered are not correct.
strMsg = String.Format("One of the following is incorrect: {0}* Username entered {0}* Password entered.", Environment.NewLine)
MessageBox.Show(strMsg, "Warning")
End Try
答案 0 :(得分:0)
您的代码中存在一些问题。
首先,如果agent_id是varchar字段,则需要在where子句中使用的值周围使用单引号,但最好避免此问题并使用parameterized query。
其次,如果你找到了什么,那么你应该使用索引0引用第一行,使用索引1引用第二列。你的代码假设数组的索引从索引1开始,但在NET世界中不是这样。 。数组总是从索引0开始。
我会尝试重写你的代码
objDataset = new Dataset()
sqlConn = "select agent_id, Password from password where agent_id = @usr"
using objConn = New MySqlConnection(....)
objConn.Open()
Try
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.SelectCommand.Parameters.AddWithValue("@usr", username)
objDataAdapter.Fill(objDataset)
if objDataset.Tables(0).Rows.Count > 0 Then
dbUsername = objDataset.Tables(0).Rows(0).Item(1).ToString
End If
End Using