我应该在哪里放置数据库连接字符串,以及如何处理连接池? [英] Where should I place my database connection string and how do I handle connection pooling?

查看:87
本文介绍了我应该在哪里放置数据库连接字符串,以及如何处理连接池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个由IIS服务器托管的asp.net应用程序。要打开连接,请使用:

I am developing an asp.net application which I have hosted on an IIS server. To open a connection I use:

SqlConnection con = new SqlConnection("Server = INLD50045747A\\SQLEXPRESS; 
Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
con.Open();

是否可以将连接字符串存储在某个地方,这样我就不需要在每个aspx中都写.cs文件?我正在使用MSSQL数据库。

Is it possible to store this connection string somewhere so that I don't need to write in every aspx.cs file? I am using MSSQL database.

我遇到的问题是:


从池中获取连接之前已经过超时时间。这可能是因为所有池化连接都在使用中,并且达到了最大池大小

The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached

我在某处阅读过,要求我增加最大值连接池达到100。这会影响我的应用程序的性能吗?

I read somewhere which asks me to increase the maximum connection pool to 100. Will it affect the performance of my application?

推荐答案

您可能没有适当地关闭打开的连接。

You probably aren't closing your open connections propertly.

增加水池大小就像在瀑布下放了一个更大的水桶-会有所帮助,但收效甚微。

Increasing the "pool size" is like putting a bigger bucket under a waterfall - it will help, but barely.

尝试查找发生这种情况的区域:

Try and locate areas where something like this is happening:

con.Open();

如果不在try / catch中,请确保它在其中,并且包括

Ensure that if it's not in a try/catch, that it is in one, and that it includes a finally statement.

try {
   con.Open();
   //several other data base releated
   //activities
} catch (Exception ex) {
  // do something
} finally {
  con.Close();
}

此外,避免最终使用 块,您可以将SqlConnection包裹在using语句中。

Also, to avoid having to use the finally block, you can just wrap the SqlConnection in a using statement.

  using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
        {

            // write your code here 

        }

关于连接字符串的问题,可以将其存储在web.config中

In regards to your question about connection string, yes store it in your web.config

<connectionStrings>
<add name="name" connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1" providerName="System.Data.SqlClient"/>
</connectionStrings>

这篇关于我应该在哪里放置数据库连接字符串,以及如何处理连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆