我正在嘗試創建一個表單,您可以在其中輸入您的員工代碼。即使員工 ID 是正確的,它仍然被錯誤地讀取。我該如何解決?這是代碼。
con.Open()
If sql = "Select * from tblempinfo WHERE EmpID ='" & Trim(TextBox1.Text) & "'" Then
MsgBox("You are now logged in ")
Me.Hide()
tito.Show()
Else
MsgBox("Invalid Employee Code")
End If
con.Close()
uj5u.com熱心網友回復:
您必須執行查詢并獲得結果。使用結果計數更有效,這意味著只需要傳遞一個數字。
您應該始終使用 SQL 引數將值傳遞給查詢,而不是將它們直接放入查詢字串中。在下面的代碼中,引數?在查詢中由 a 表示- 代碼不使用引數的名稱(“@empid”),但它可以幫助您在有多個時查看哪個是哪個。
Dim sql = "SELECT COUNT(*) FROM tblempinfo WHERE EmpID = ?"
Dim n = 0
Using conn = New OleDbConnection("yourConnectionString"),
cmd = New OleDbCommand(sql, conn)
Dim empId = TextBox1.Text.Trim()
cmd.Parameters.Add("@empid", OleDbType.VarWChar).Value = empId
conn.Open()
n = CInt(cmd.ExecuteScalar())
End Using
If n = 1 Then
MsgBox("You are now logged in ")
Me.Hide()
tito.Show()
Else
MsgBox("Invalid Employee Code")
End If
請OleDbType.VarWChar根據需要調整以匹配資料庫列的實際型別。
uj5u.com熱心網友回復:
您可能需要檢查用戶的身份驗證級別,并確保只有一條記錄。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim input = TextBox1.Text.Trim()
Dim empID As Integer
' need to validate the text input as integer
If Integer.TryParse(input, empID) AndAlso isUserAuthenticated(empID) Then
MsgBox("You are now logged in ")
Me.Hide()
tito.Show()
Else
MsgBox("Invalid Employee Code") ' TextBox.Text incorrect format
End If
End Sub
Private Function isUserAuthenticated(empID As Integer) As Boolean
Using con As New SqlClient.SqlConnection("connection string") ' put your connection string here
Dim sql = "Select * from tblempinfo WHERE EmpID = @empID"
Using com As New SqlClient.SqlCommand(sql, con)
con.Open()
com.Parameters.AddWithValue("@empID", empID)
Dim dr = com.ExecuteReader()
Dim results As New List(Of Object)()
While dr.Read()
results = dr.GetValue(0) ' index of result you will use to authenticate user
End While
If results.Any() Then
If results.Count = 1 Then
Dim result = DirectCast(results(0), Integer) ' assuming the result is an integer
If result > 5 Then ' arbitrary here, but assuming > 5 means authenticated
Return True
Else
Return False ' not authenticated
End If
Else
Return False ' > 1 record
End If
Else
Return False ' no records
End If
End Using
End Using
End Function
uj5u.com熱心網友回復:
請按此順序檢查以下事項:-
- 如果代碼沒有出錯,那么 -
a) 首先使用 db.OpenRecordset() 打開您嘗試訪問的 SQL 的記錄集
b) 如果記錄集上沒有資料,驗證錯誤場景 IsNull()
c) 如果您到達第三步,則檢查表中是否有超過 1 行的相同員工代碼 - RecordCount > 0。如果在這種情況下記錄集回傳 > 1 行,則請處理錯誤情況
d) 將代碼中的上述每一步都按照相同的順序處理,請不要試圖直接到達最終狀態,因為它會幫助您一起理解代碼和資料流。
e) 如果仍然存在一些問題,則嘗試洗掉修剪并嘗試輸入正確的員工代碼并檢查在此特定情況下是否可以正常作業。
- 如果是案例代碼出錯,請修復代碼并重試。
- 您已經提到資料讀取不正確,這似乎表明沒有錯誤,但回傳的資料不正確。因此,請提供有關您的輸入和輸出內容的其他資訊,以便提供更多建議。但我仍然建議您處理上述建議的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/384923.html
