2017-07-26 98 views
-2

哪一個合適?我需要關於ADO.net的幫助

Methot 1

Dim Connection As New SqlConnection 
Dim CMD As New SqlCommand 
Connection = New SqlConnection(My.Settings.ConnectionString) 
CMD = Connection.CreateCommand() 
CMD.Connection.Open() 

CMD.CommandText = "Insert Into TableName................." 
CMD.ExecuteNonQuery() 
CMD.CommandText = "Update TableName Set................." 
CMD.ExecuteNonQuery() 

Connection.Close() 
Connection.Dispose() 
CMD.Dispose() 

Methot 2

Dim Connection As New SqlConnection 
Dim CMD As New SqlCommand 
Connection = New SqlConnection(My.Settings.ConnectionString) 
Connection.Open() 
CMD = Connection.CreateCommand() 

CMD.CommandText = "Insert Into TableName................." 
CMD.ExecuteNonQuery() 
CMD.CommandText = "Update TableName Set................." 
CMD.ExecuteNonQuery() 

Connection.Close() 
Connection.Dispose() 
CMD.Dispose() 

兩種方法都工作得很好。但我很困惑使用哪一個。請幫忙。

+0

有什麼區別? – David

+0

好的......你爲什麼認爲*有區別?解釋你在問什麼。我發現這兩者之間唯一不同的是你交換了創建查詢對象的行並打開連接。這兩條線的順序本身並不重要。 – David

+0

1.使用命令打開連接 2.使用SQLConnection打開連接 –

回答

0

正如David在評論中提到的那樣,兩種方法之間沒有功能上的區別。

這兩種方法都在相同的SqlConnection對象上調用.Open()。他們只是在創建SqlCommand 對象之前或之後執行此操作。創建SqlCommand對象並打開連接 不依賴於彼此,所以順序沒有什麼區別。