看看下面的例子...
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", SqlDbType.Int, 4)
.Parameters("@CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
从我的研究是当今的声音,仿佛这基本上是好的,但在SqlCommand的没有被处理掉。
问题 - >下列哪个例子是对付它的最好方法?
实施例2 - 手动处置
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", SqlDbType.Int, 4)
.Parameters("@CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
cmd.Dispose()
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
例3 - 自动与使用的语句处置
Using cn As New SqlConnection(ConnectionString)
Try
Using cmd As New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", SqlDbType.Int, 4)
.Parameters("@CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
End Using
Catch ex As Exception
End Try
End Using
实施例4 - 同实施例3,但的try / catch是内使用 - 这是否有所作为?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand
Try
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", SqlDbType.Int, 4)
.Parameters("@CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
例5 - 同样作为例子4,但在CommandText和cn在using语句指定的 - 这是否有什么优势?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection.Open()
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", SqlDbType.Int, 4)
.Parameters("@CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
实施例6 - 同实施例5,但打开连接于CN代替CMD。 它是更好地打开,如果只有一个存储过程是要执行CMD上的连接?
Using cn As New SqlConnection(ConnectionString)
cn.Open()
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection = cn
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", SqlDbType.Int, 4)
.Parameters("@CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using