【发布时间】:2013-03-14 18:41:56
【问题描述】:
在 C# 中为 SQL 连接使用 using 块时,这是否也是一种关闭方法?我在问,因为我需要明确使用 con.Open() 方法。我找到了这个例子:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open(); // open method
string queryString = "select * from db";
SqlCommand cmd = new SqlCommand(queryString, con);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
??? // What about a close method?
}
或者using 块是否会自行关闭连接?
【问题讨论】:
-
using 将调用 Dispose 的连接,而 Dispose 将调用 Close。
-
所以当我使用它时,使用将关闭所有连接。所有连接都意味着全局,还是只有这个方法/类中的这个连接在哪里?
-
@ManuelFischer 仅使用语句连接(SqlConnection iWillDisposeConn = new...
-
你真的应该在
using块中拥有你的命令和阅读器 - 它们也是一次性的。
标签: c# sql connection using