【发布时间】:2015-09-08 22:33:57
【问题描述】:
我能做到吗:
using connection
myDt1 = sqlSelect(connection, sql)
myDt2 = sqlSelect(connection, sql)
end using
使用 SQLSelect :
Public Shared Function SQLSelect(ByVal provider As SqlConnection, ByVal strSQL As String, ByVal ParamArray params() As SqlParameter) As DataTable
Using connection = provider
SQLSelect = New DataTable
Dim dtReader As SqlDataReader
Dim command As SqlCommand = CreateSQLCommand(provider, strSQL, params)
Try
connection.Open()
dtReader = command.ExecuteReader()
SQLSelect.Load(dtReader)
dtReader.Close()
Catch ex As Exception
SQLSelect = Nothing
Finally
'If connection.State = ConnectionState.Open Then
' connection.Close()
'End If
command.Dispose()
End Try
End Using '<--- Here drop connection
Return SQLSelect
因为在SQLSelect函数中,在使用结束时,连接断开了! 所以当我尝试连接到第二个查询时出现错误。
谢谢
【问题讨论】:
-
您正在关闭 SqlSelect 中的连接。Using 的全部意义在于为您关闭和处理连接。
-
这两行忘记注释了,drop connection append在en using end上,很奇怪,参数是ByVal,不是吗?
-
如果我每次都传递连接字符串而不是sqlconnection会更好吗?
-
您最好将 ~connection.Open()~ 从 SqlSelect 中取出并传递给 SqlSelect 一个打开的连接。同时从 SqlSelect 中删除 Using 和 EndUsing
-
最后一个问题,如果我在不同的类中有 3 个函数:-Main() -> 调用例如 ListAllData() -
ListAllData -> execute SQLSelect(sqlconnection, parameters) -> which open connection and execute the query in the last classe with SQLSelect---- -SQLSelect -> which execute是正确的和好的练习?
标签: vb.net data-access-layer using sqlconnection