在 static void 中声明数据库连接 - 连接池会持续存在吗?
我有一台多线程服务器,它使用每个客户端都应该有权访问的一个 MSSQL。我想使用连接池,我也正在使用这个:
public static void DBconn()
{
SqlConnection pripojeni = new SqlConnection();
pripojeni.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=XYZ;Trusted_Connection=True;Min Pool Size=20";
}
如果连接字符串声明“min pool”,该对象是否会保留在内存中(不是对象本身而不是打开的连接)?还是用完这个方法就没有了?谢谢
I have a multithread server that uses one MSSQL which each client should have access to. I wanted to use connection pooling also I am using this:
public static void DBconn()
{
SqlConnection pripojeni = new SqlConnection();
pripojeni.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=XYZ;Trusted_Connection=True;Min Pool Size=20";
}
Does the object will persist in memory (not the object itself rather than the open connections) if connection strings states "min pool"? Or will it be gone after finishing this method? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该为每个连接使用一个新的
SqlConnection
对象,而不是在静态构造函数中创建一个对象。当您创建的每个连接都使用相同的连接字符串时,连接池就会起作用(您应该将其存储在 web.config 或 app.config 等配置文件中)。只需每次创建并打开一个
SqlConnection
对象,记住在最后关闭/处置它,连接池将确保它重新使用现有的、打开的连接。希望有帮助!
You should use a new
SqlConnection
object for each connection, not create one in the static constructor. Connection Pooling works when each connection you create uses the same connection string (you should store it in a configuration file like web.config or app.config).Just create and open a
SqlConnection
object each time, remember to close/dispose it at the end, and connection pooling will ensure that it re-uses existing, open connections.Hope that helps!
由于您在此方法中新声明了 SqlConnection 对象,因此该对象将在方法结束后消失。
尝试这个持续连接:
注意:我同意 Kieren 的观点,如果你始终保持连接打开,你会堵塞数据库,(几乎总是)每次打开和关闭要好得多。
Since you newly declared the SqlConnection object in this method it will be gone after the method ends.
try this for a continued connection:
Note: I agree with Kieren, if you keep your connection open at all time, you will clog the database, it's (almost always) much better to open and close each time.