2011-11-09 31 views
0

我需要一些幫助,正確實施與強類型的TableAdapter使用說明和TableAdapter的連接

USING語句我有這樣的事情:

Using myDT As New mbr_Account.mbr_AccountDataTable 
    Using myTA As New mbr_AccountTableAdapters.mbr_AccountTableAdapter 
      myTA.Connection.Open() 
      myTA.Fill(myDT) 
      myTA.Connection.Close() 
    End Using 

    For Each row In myDT 
      'do stuff 
    Next 
End Using 

這會正確處理的數據表和TableAdapter的,但不沒有解決連接對象的問題。

我該如何處置Connection對象?

我可以換最後像這樣在嘗試連接...:

Using myDT As New mbr_Account.mbr_AccountDataTable 
    Using myTA As New mbr_AccountTableAdapters.mbr_AccountTableAdapter 
     Try 
      myTA.Connection.Open() 
      myTA.Fill(myDT) 
     Finally 
      If Not IsNothing(myTA.Connection) Then 
       myTA.Connection.Close() 
       myTA.Connection.Dispose() 
      End If 
     End Try 
    End Using 

    For Each row In myDT 
     'do stuff 
    Next 
End Using 

問:我如何使用using關鍵字,而不是嘗試。最後的連接對象?

回答

0

我剛剛發現TableAdapter自動處理連接的打開和關閉,並且不需要手動添加代碼。

基本上,它們已經包含Try ... finally塊來處理異常期間關閉連接。

設計器生成插入/刪除/更新的代碼如下所示:

global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State; 
    if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open) 
       != global::System.Data.ConnectionState.Open)) { 
     this.Adapter.InsertCommand.Connection.Open(); 
    } 
    try { 
     int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery(); 
     return returnValue; 
    } 
    finally { 
     if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { 
      this.Adapter.InsertCommand.Connection.Close(); 
     } 
    } 

因此無需關閉或出售的連接對象。

0

任何你不能使用DataReader的理由?

Dim sql As String = "SELECT whatever FROM SomeTable" 
Using myConnection As New SqlConnection(MyConnectionstring) 
    Using myCommand As New SqlCommand(sql, myConnection) 
     myConnection.Open() 
     Using myReader As SqlDataReader = myCommand.ExecuteReader() 
      Dim myTable As New DataTable() 
      myTable.Load(myReader) 
      myConnection.Close() 
      Return myTable 
     End Using 
    End Using 
End Using 

連接將被關閉並自動處置。

+0

不,我想知道如何用TableAdapters來做到這一點。 –