Mik*_*ike 8 c# using using-statement
我知道很多例子都存在,其中定义了SqlConnection,然后在Using块中定义了SqlCommand:
using (var conn = new SqlConnection(connString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
//open the connection
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题:如果我直接在SqlCommand上定义连接,那么当命令被释放时连接是否会关闭?
using (var cmd = new SqlCommand()) {
cmd.Connection = new SqlConnection(connString);
//open the connection
}
Run Code Online (Sandbox Code Playgroud)
它不会关闭连接,您需要自己关闭它或使用 statment 将其放在自己的位置。
这里还有一个技巧可以让你的using块更具可读性:
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5005 次 |
| 最近记录: |