使用说明和TableAdapter的连接
问题描述:
我需要一些帮助,正确实施与强类型的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关键字,而不是尝试。最后的连接对象?
答
我刚刚发现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();
}
}
因此无需关闭或出售的连接对象。
答
任何你不能使用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
连接将被关闭并自动处置。
不,我想知道如何用TableAdapters来做到这一点。 –