我在ADO.net上需要帮助

时间:2017-07-26 17:19:27

标签: ado.net vb.net-2010 sqlclient

哪一个合适?

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()

这两种方法都运行得很好。但我很困惑使用哪一个。请帮忙。

1 个答案:

答案 0 :(得分:0)

正如David的评论中所提到的,两种方法之间没有功能差异。

  

这两种方法都在同一个SqlConnection上调用.Open()   宾语。他们只是在创建SqlCommand之前或之后执行此操作   宾语。创建SqlCommand对象并打开连接   不依赖于彼此,所以顺序没有区别。