为什么SQLHelper.vb中没有ExecuteDataTable的共享函数?有一个: ExecuteReader,ExecuteDataset和ExecuteScaler。
这不是问题,因为我会写我自己的。我只是想知道为什么会这样。我通常会使用DataReader,但我正在编写一个数据逻辑层,并且DataTable需要比连接更持久(DataReaders不能比连接更持久)。
发布于 2013-01-16 01:48:12
ExecuteDataset()已经可以做你需要的事情了。从某种意义上说,数据集就是DataTables的集合。
我通常会使用DataReader,但我正在编写一个数据逻辑层,并且DataTable需要比连接更持久(DataReaders不能比连接更持久)。
在这种情况下,我建议您构建一个在迭代器块中使用DataReader的ExecuteEnumerable()方法,而不是构建一个ExecuteDatatable()方法。代码将如下所示:
Public Shared Iterator Function ExecuteEnumerable(Of T)( ... ) As IEnumerable(Of T)
Using cn As New SqlConnection( ... ), _
cmd As New SqlCommand( ... )
'As needed
'cmd.Parameters.Add( ... ).Value = ...
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Yield transform(rdr)
End While
End Using
End Using
End Function你会注意到我跳过了一些东西。我不熟悉现有的SqlHelper.vb文件,因为您希望与现有的样式相匹配,所以我在代码中为您留出了适应的空间。然而,我想指出两个重要的部分:
transform(rdr)调用将使用Func(IDataRecord, T)委托,该委托必须作为参数提供给函数。要使ExecuteEnumerable()迭代器概念起作用,您必须在每次迭代时复制SqlDataReader对象中的当前值。您可以在这里设置某种通用数据传输对象,就像在DataTable中使用的DataRow类型一样。但是,与其花费cpu和内存时间将副本创建到某种类型的通用数据传输对象中,我更喜欢使用委托让代码直接将其复制到强类型的业务对象中。缺点是需要在每次调用方法时发送指令,说明如何为特定对象执行此操作。不过,大多数情况下,使用业务对象上的共享工厂方法就可以很容易地做到这一点。发布于 2015-06-13 04:16:34
我们可以像这样创建与DataSet相同的内容
' Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
' using the provided parameters.
' e.g.:
' Dim dt As DataTable = ExecuteDataTable(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24))
' Parameters:
' -connection - a valid SqlConnection
' -commandType - the CommandType (stored procedure, text, etc.)
' -commandText - the stored procedure name or T-SQL command
' -commandParameters - an array of SqlParamters used to execute the command
' Returns: A dataset containing the resultset generated by the command
Public Overloads Shared Function ExecuteDataTable(ByVal connection As SqlConnection, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal ParamArray commandParameters() As SqlParameter) As DataTable
If (connection Is Nothing) Then Throw New ArgumentNullException("connection")
' Create a command and prepare it for execution
Dim cmd As New SqlCommand
Dim dt As New DataTable
Dim dataAdatpter As SqlDataAdapter
Dim mustCloseConnection As Boolean = False
PrepareCommand(cmd, connection, CType(Nothing, SqlTransaction), commandType, commandText, commandParameters, mustCloseConnection)
Try
' Create the DataAdapter & DataSet
dataAdatpter = New SqlDataAdapter(cmd)
' Fill the DataSet using default values for DataTable names, etc
dataAdatpter.Fill(dt)
' Detach the SqlParameters from the command object, so they can be used again
cmd.Parameters.Clear()
Finally
If (Not dataAdatpter Is Nothing) Then dataAdatpter.Dispose()
End Try
If (mustCloseConnection) Then connection.Close()
' Return the dataset
Return dt
End Function ' ExecuteDataTablehttps://stackoverflow.com/questions/14343470
复制相似问题