2009-02-27 182 views
2

我熟悉VB6 ADO處理SQL查詢和循環記錄集結果的方式。vb.net循環查詢結果

但是,什麼是正確的方式來查詢服務器,遍歷結果,並在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 

回答

7

我懷疑問題與您管理gconIntegration連接做。你正在努力繼續使用相同的連接。看看它的位置會很有幫助。

更好地從池中獲得「新」連接並讓.NET爲您擔心。

此外,您的通用「GetSQLTable」代碼缺少一個重要部分:它不允許設置參數,它告訴我您將它們直接構建到查詢字符串中。這是一場災難:它將導致Sql注入安全漏洞。

還有一件事:不要在.Net中將對象設置爲Nothing。要麼根據需要處理它們,要麼讓它們自己掉到範圍之外。

這是我從一個數據表中拉回來一個DataTable正常方法:

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
  • 查詢參數保持強類型,並且從不將直接替換爲查詢字符串,即使它們傳輸到服務器。 Sql數據和Sql代碼從不混合。
  • 對於每個需要發送的查詢,您都需要單獨的函數。這真是一件好事,因爲它會導致爲數據庫構建強類型的接口。理想情況下,所有這些函數都在同一個類中,並且GetConnectionString函數對於該類是私有的。在這個數據層之外沒有數據庫訪問發生。
+0

gconIntegration是一個全局連接。所以你說我所有閱讀和寫作的單一連接並不是最佳途徑? – 2009-02-27 21:11:56