与数据库建立连接的不同方法 [英] Different ways to make a connection to the database

查看:61
本文介绍了与数据库建立连接的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





 Dim conn As New SqlConnection(Acc.Common.Configuration.Instance.ConnectionString) 

,如果为了操作连接我使用下面的代码会有什么不同:



 如果 conn.State = ConnectionState.Closed 然后 
conn.Open()
结束 如果





或者我可以简单地使用以下代码:



 conn.Open()





我想这两种方式都有效,但在逻辑方面呢它有什么不同吗?



谢谢,



我尝试过:



两种情况都适合我,但我只想问哪种方式更好。

解决方案

在正常情况下,它应该无关紧要 - 因为无论如何使用使用块来创建实例是一个非常好的主意:

 使用 con 作为  SqlConnection(Acc.Common.Configuration.Instance.ConnectionString)
con.Open()
使用 com As SqlCommand( SELECT iD,description from myTable,con)
...
End 使用
结束 使用

因为它确保连接始终处于关闭状态并在完成后处理。

因为您创建它,打开它并使用它 - 然后t他的系统会自动关闭并处理它没有任何问题。

但是......如果在你打开Open时打开连接,它会抛出一个InvalidOperationException


Hi,

Dim conn As New SqlConnection(Acc.Common.Configuration.Instance.ConnectionString)



in vb.net while using the ado does and working with a connection, does it make any difference if for oppening a connection I use the code below:

If conn.State = ConnectionState.Closed Then
conn.Open()
End If



or can I simply use the following code:

conn.Open()



I guess that both ways it works, but in the logic does it make any different?

thanks,

What I have tried:

Both cases are working for me but I'm just asking which way is better.

解决方案

Under normal circumstances, it shouldn't matter - because it's a very good idea to use a Using block around the creation of the instance anyway:

Using con As New SqlConnection(Acc.Common.Configuration.Instance.ConnectionString)
	con.Open()
	Using com As New SqlCommand("SELECT iD, description FROM myTable", con)
                ...
	End Using
End Using

Because it ensures that the connection is always closed and Disposed when you are finished with it.
Because you create it, open it, and use it - then the system automatically closes and disposes of it there isn't any problem.
But...if the connection is open when you call Open on it, it will throw an InvalidOperationException


这篇关于与数据库建立连接的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆