[英]Compare array with SQl table
對於名為ALLconn的數組中的每個連接,我想將其與sql表進行比較。 如果存在,則添加到我的列表視圖。 這是下面的代碼,但似乎不起作用:
Dim LoginFilter As Object
Dim SelCurrAllSessions As SqlClient.SqlCommand = New SqlClient.SqlCommand("Select * from CurrAllSessions", LFcnn)
SelCurrAllSessions.CommandType = CommandType.Text
LoginFilter = SelCurrAllSessions.ExecuteReader
For Each conn In AllConn
While LoginFilter.Read()
If conn.UserName.ToString() = LoginFilter.Item(0) Then
ListBox1.Items.Add(LoginFilter.Item(0))
End If
End While
Next
好了,您需要更改循環的順序
While LoginFilter.Read()
For Each conn In AllConn
If conn.UserName.ToString() = LoginFilter.Item(0).ToString Then
ListBox1.Items.Add(LoginFilter.Item(0).ToString)
Exit For
End If
Next
End While
這是必要的,因為在您的原始代碼中,內部運行會一直運行到從數據庫加載的數據結束時為止,然后,當您嘗試檢查下一個conn時,您將無法在數據庫加載的數據的開頭重新定位讀取器。
與此相反,使用Contains
檢查字符串是否包含在集合中,然后可以將其添加到ListBox
:
Using LoginFilter = SelCurrAllSessions.ExecuteReader()
While LoginFilter.Read()
Dim connection = LoginFilter.GetString(0)
If AllConn.Contains(connection) Then
ListBox1.Items.Add(connection)
End If
End While
End Using
實際上,您的問題尚未完成,但是根據我的理解,您仍然試圖讀取SqlCommand.ExecuteReader()的結果。 當您讀取該結果時,它將從頭到尾讀取,這只能讀取一次。 如果嘗試再次讀取,則會顯示錯誤,因為沒有更多內容可從對象Loginfilter讀取。
因此,您可以將該讀數存儲到數組中,然后繼續使用Foreach和新創建的數組進行邏輯處理,或者可以從LoginFilter中讀取並比較到AllConn數組或List中的Forech連接。
如果您需要更多說明,請隨時回復我,我將以C#版本發送給您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.