我想返回一個List(Of DataTable)使用SqlDataReader而不是填充數據集。當它正確地檢索到4個表格後,我收到「無法嘗試在讀取器關閉時調用讀取」錯誤。下面是我使用無法嘗試打開閱讀器關閉時的讀取。 ExecuteReader獲取多個表結果
Private Function ExecuteDS(ByVal SPName As String, ByVal ParamList As List(Of System.Data.SqlClient.SqlParameter)) As List(Of System.Data.DataTable)
Dim ds As New List(Of System.Data.DataTable)
Dim dbConStr As Database
dbConStr = New Database()
Using con As New System.Data.SqlClient.SqlConnection(dbConStr.ReturnString)
Dim cmd As New System.Data.SqlClient.SqlCommand(CStr(SPName), con)
cmd.CommandType = System.Data.CommandType.StoredProcedure
cmd.CommandTimeout = 30
For Each p As System.Data.SqlClient.SqlParameter In ParamList
cmd.Parameters.Add(p)
Next
con.Open()
Using dr As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
Do While dr.Read()
Dim dt As New System.Data.DataTable
dt.Load(dr)
ds.Add(dt)
Loop
End If
End Using
con.Close()
End Using
Return ds
End Function
在dr.Read()
發生錯誤的功能。它應該返回4個表格,但在獲得第4個表格後,它仍然會嘗試執行dr.Read()
並引發錯誤,而不是僅僅正確退出循環。任何見解,我將不勝感激,謝謝。
編輯:也試過這與dr.NextResult()並仍然在同一行中獲取錯誤。
Using dr As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader
Do While dr.HasRows
Do While dr.Read()
Dim dt As New System.Data.DataTable
dt.Load(dr)
ds.Add(dt)
Loop
dr.NextResult()
Loop
End Using
編輯2:在IF語句dr.HasRows試過,在dr.Read()仍然得到錯誤...
Using dr As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader
Do
If dr.HasRows Then
While dr.Read()
Dim dt As New System.Data.DataTable
dt.Load(dr)
ds.Add(dt)
End While
End If
Loop While dr.NextResult()
End Using
您應該使用['DataReader.NextResult'(http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.data.framework.datareader.nextresult.ASPX) – Habib
當我使用它,它會在我的結果中跳過表格。它從我的結果中返回表0和表2,所以我沒有從結果集中得到表1和3。 – bflosabre91
嘗試DataTableReader不是DataReader DataRow。 http://msdn.microsoft.com/en-us/library/4e06d41f.aspx – Paparazzi