当命令被处理并且连接是直接在命令上定义时,连接是否会关闭?
我知道有很多例子,其中定义了 SqlConnection,然后定义了 SqlCommand,两者都在使用块中:
using (var conn = new SqlConnection(connString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
//open the connection
}
}
我的问题:如果我直接在 SqlCommand 上定义连接,则在处理命令时连接会关闭吗?
using (var cmd = new SqlCommand()) {
cmd.Connection = new SqlConnection(connString);
//open the connection
}
I know that a lot of examples exist where a SqlConnection is defined and then a SqlCommand is defined, both in Using blocks:
using (var conn = new SqlConnection(connString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
//open the connection
}
}
My question: If I define the connection directly on the SqlCommand, does the connection close when the command is disposed?
using (var cmd = new SqlCommand()) {
cmd.Connection = new SqlConnection(connString);
//open the connection
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,SqlCommand 从不尝试关闭/处置连接。
No, SqlCommand never attempts to close/dispose of the connection.
不,除非您显式处置连接对象,否则不会对其进行处置。 但我的建议是尽可能使用使用块。
No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.
它不会关闭连接,您需要自己关闭它或将其放在自己的 using 语句中。
另外,这里还有一个技巧,可以让您的
using
块更具可读性:It does not close the connection, you need to either close it yourself or put it in its own using statment.
Also here is a tip to make your
using
blocks a bit more readable:@米洛特
使用“使用块”很好,但在处理非 IDisposable 对象时毫无用处,因此如果您在任何地方使用“使用块”,这可能会令人困惑。
请小心,因为如果您的对象未实现 IDisposable,则它们可能不会被释放。
希望这可以帮助。
@milot
Using Using Blocks is nice but useless when working with non IDisposable Objects and so this can be confusing if you use Using Blocks anywhere.
Be careful since your objects might not being Disposed if they don't implements IDisposable.
Hope this helps.