为什么SqlConnection会忘记数据库类型
我最近发布了一个关于 SqlConnection 在“ChangeDatabase”范围结束时丢失其数据库信息的问题(当我认为该问题与实际问题无关时,立即删除)。示例:
//Other code...
dbConn = new SqlConnection(dbConnBuilder.ConnectionString);
dbConn.Open();
dbConn.ChangeDatabase(currentDatabase);
dbConn.Close();
}
我的问题:
- 当您只拥有给定类型的一个连接时,保留 SqlConnection 对象并在需要时打开和关闭它是否被视为不好的做法?
- 为什么在 ChangeDatabase(方法而不是变量)“超出范围”之后
dbConn.Database
不记住currentDatabase
'? (哎呀,我不知道像ChangeDatabase
这样的方法可以了解范围)。
我的连接字符串是:
Data Source=server.name.com;Persist Security Info=True;User ID=username;Password=password
谢谢大家,请告诉我是否可以为您提供更多信息,仍在学习使用 SO
I recently posted (and promptly deleted, when I decided the question was irrelevant to the actual problem) a question about SqlConnection losing its Database information when the scope of "ChangeDatabase" ends. Example:
//Other code...
dbConn = new SqlConnection(dbConnBuilder.ConnectionString);
dbConn.Open();
dbConn.ChangeDatabase(currentDatabase);
dbConn.Close();
}
My questions:
- Is it considered bad practice to hold onto a
SqlConnection
object and open and close it whenever you need it when you'll only ever have ONE connection of a given type? - Why does
dbConn.Database
not remembercurrentDatabase
after ChangeDatabase (a method not a variable) 'Goes out of scope'? (Heck, I didn't know methods likeChangeDatabase
could know about scope).
My connection string was:
Data Source=server.name.com;Persist Security Info=True;User ID=username;Password=password
Thanks guys, let me know if I can give you more information, still learning to use S.O.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
Close()
会完全销毁该对象,因此您之后不应读取其任何属性。事实上,甚至应该有一个“after”,因为您不应该调用
Close()
。相反,在using
块中实例化连接,以便它调用Dispose()
,这与Close()
执行相同的操作,但无论您如何离开街区,都保证会这样做。Calling
Close()
completely destroys the object, so you should not be reading any of its properties after.In fact, there should even be an "after" because you shouldn't be calling
Close()
. Instead, instantiate the connection in ausing
block, so that it'll callDispose()
, which does the same thing asClose()
, but is guaranteed to do so no matter how you leave the block.因此,只需确保每次需要执行语句时都调用changedatabase:-)
So just make sure to call changedatabase every time you need to execute a statement :-)