[英]vb.net cycle through query results
我熟悉VB6 ADO處理SQL查詢和遍歷記錄集結果的方式。
但是,查詢服務器,循環搜索結果以及在VB.Net中處理查詢的正確方法是什么? 我一直在使用的所有方法似乎都很不穩定,並且隨機崩潰。
我一直在使用以下代碼:
Public Function GetSQLTable(ByVal strSQL As String) As DataTable
Dim table As New DataTable
Dim adapt As SqlDataAdapter
Try
adapt = New SqlDataAdapter(strSQL, gconIntegration)
adapt.Fill(table)
Catch ex As Exception
LogError("GetSQLTable: " & ex.ToString(), "SQL: " & strSQL)
End Try
Return table
End Function
並像這樣使用它:
Dim dt As DataTable
Dim lngRow As Long
Dim current As DataRow
Dim lngContact As long
Try
dt = GetSQLTable(strSQL)
For lngRow = 0 To dt.Rows.Count - 1
current = dt.Rows.Item(lngRow)
lngContact = current.Item("indvid")
DoSomething(lngContact)
Next
Catch ex As Exception
LogError("FindContact: " & ex.ToString(), "SQL: " & strSQL)
lngContact = -1
Finally
current = nothing
dt = nothing
我懷疑問題與您如何管理gconIntegration
連接有關。 您正在努力嘗試繼續使用相同的連接。 看看它住的地方會很有幫助。
最好從池中獲取“新”連接,然后讓.Net為您擔心。
同樣,您的通用“ GetSQLTable”代碼缺少重要部分:它不允許設置參數,這告訴我您是將它們直接構建到查詢字符串中。 那是災難的秘訣:它將導致Sql注入安全漏洞。
還有一件事:不要在.Net中將對象設置為Nothing
。 如有必要,可以將其處置,或者讓它們自己脫離范圍。
這是從數據表中拉回數據表的正常方法:
Function GetSomeData(ByVal Table2ID As Integer)
Dim result As New DataTable
Dim sql As String = "SELECT Column1,Column2 FROM [Table1] WHERE Table2ID= @Table2ID"
Using cn As New SqlConnection( GetConnectionString() ), _
Using cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("@Table2ID", SqlDbType.Int).Value = Table2ID
Using rdr As SqlDataReader = cmd.ExecuteReader()
result.Load(rdr)
End Using
End Using
return result
End Function
關於該代碼的一些注釋:
Using
語句將確保將關聯的對象放置在相應的End Using
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.