看看下面的例子...的SqlCommand(using語句/處置問題)
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相同,但在Using語句中指定了CommandText和cn - 它具有哪些優點?
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
using語句更安全,但在大多數情況下,阻止忽略所有異常的try/catch是不鼓勵的。所以你怎麼把你的嘗試抓住一切取決於你想要完成什麼。你有什麼問題? –
這個問題在我看來更適合codereview.stackexchange.com –
空的try/catch只是一個例子,但在這種情況下,它只是爲了安全。在這個過程的外部,我要檢查的是包含任何表的數據集。如果沒有,我會妥善處理。關於這個問題,它是最重要的 - 我在問什麼是處理SqlCommand處置的最好方法。我個人認爲例5是正確的,但想知道別人的反饋。 –