我需要一些帮助才能正确实现强类型TableAdapters
的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对象?
我可以在Try中包装连接...最后像这样:
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关键字代替Try ..最后是连接对象?
答案 0 :(得分: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
连接将被关闭并自动处理。
答案 1 :(得分:0)
我刚刚发现TableAdapters会自动处理连接的打开和关闭,无需手动添加代码。
基本上,它们已经包含Try ... Finally块来处理异常期间的连接关闭。
Designer生成的插入/删除/更新代码如下所示:
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();
}
}
因此无需关闭或处置连接对象。