简体   繁体   English

我应该在哪里放置我的数据库连接字符串以及如何处理连接池?

[英]Where should I place my database connection string and how do I handle connection pooling?

I am developing an asp.net application which I have hosted on an IIS server.我正在开发一个 asp.net 应用程序,该应用程序托管在 IIS 服务器上。 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();

Is it possible to store this connection string somewhere so that I don't need to write in every aspx.cs file?是否可以将此连接字符串存储在某处,以便我不需要写入每个 aspx.cs 文件? I am using MSSQL database.我正在使用 MSSQL 数据库。

I'm facing an issue which says:我面临一个问题,它说:

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这可能是因为所有池连接都在使用中并且达到最大池大小

I read somewhere which asks me to increase the maximum connection pool to 100. Will it affect the performance of my application?我在某处读到要求我将最大连接池增加到 100。它会影响我的应用程序的性能吗?

Store it in the web.config file, in the connectionStrings section:将其存储在web.config文件的connectionStrings部分中:

<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>

And then you will be able to access this in your code...然后您将能够在您的代码中访问它...

ConfigurationManager.ConnectionStrings["name"].ConnectionString

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();

Ensure that if it's not in a try/catch, that it is in one, and that it includes a finally statement.确保如果它不在 try/catch 中,则它在一个中,并且包含 finally 语句。

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

Also, to avoid having to use the finally block, you can just wrap the SqlConnection in a using statement.此外,为了避免使用finally块,您可以将 SqlConnection 包装在 using 语句中。

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

            // write your code here 

        }

In regards to your question about connection string, yes store it in your web.config关于您关于连接字符串的问题,是的,将其存储在您的 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>

you can do using also你也可以使用

it will automatically disposes the object它将自动处理 object

if you use "using" there is no need of con.close and all如果您使用“使用”,则不需要 con.close 和所有

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

     // write your code here 

        }

Store the connection string in the web.config files.将连接字符串存储在 web.config 文件中。 you can find numerous examples.你可以找到很多例子。 Check this for the properties.检查此属性。 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.71%29.aspx http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.71%29.aspx

Thanks Shankar谢谢尚卡尔

Use the Help of Both使用两者的帮助

try
{
 con.Open();
}
catch(Exception ex)
{
if(con.State== ConnectionState.Open)
con.Close();
}
finally
{
con.Close();
}

and also add the Connection String in Web.Config, under Configuration.并且还在配置下的 Web.Config 中添加连接字符串。 This will help you.这将对您有所帮助。

Yes, store it in the web.config file but make sure that if there is an error it doesn't display the content of the web.config file to the user (thus showing the world your password.)是的,将其存储在 web.config 文件中,但请确保如果出现错误,它不会向用户显示 web.config 文件的内容(从而向全世界展示您的密码。)

If you use that same connection string in a lot of applications you could consider writing a service to provide the connection strings, that way you only have to change them in one place.如果您在许多应用程序中使用相同的连接字符串,您可以考虑编写一个服务来提供连接字符串,这样您只需在一个地方更改它们。

The best option is to use typed settings.最好的选择是使用键入的设置。

Open your project properties.打开您的项目属性。
Go to Settings tab. Go 到设置选项卡。
Add new setting, for example MainConnectionString , select setting type (ConnectionString) .添加新设置,例如MainConnectionString 、 select 设置类型(ConnectionString) In the value insert your connection string or hit '...' button to bring a dialog to build connection string.在值中插入您的连接字符串或点击“...”按钮以打开一个对话框来构建连接字符串。

Now you can reference your connection string in the code like this:现在您可以在代码中引用您的连接字符串,如下所示:

Settings.Default.MainConnectionString

If you open your config file you will see如果你打开你的配置文件,你会看到

  <configuration>
    <connectionStrings>
      <add name="WebApplication1.Properties.Settings.MainConnectionString"
           connectionString="Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True"
           providerName="System.Data.SqlClient" />
    </connectionStrings>

You can have this connection string specified:您可以指定此连接字符串:

  • for one web site in its own web.config.一个 web 站点在其自己的 web.config 中。
  • for a group of web sites对于一组 web 站点
  • for all web sites on a box: in machine scope web.config.对于一个盒子上的所有 web 站点:在机器 scope web.config 中。
  • for all application on a box: in the machine.config.对于一个盒子上的所有应用程序:在 machine.config 中。

This can be convenient if you have a lot of applications that connect to the same db and are installed on one box.如果您有很多应用程序连接到同一个数据库并安装在一个盒子上,这会很方便。 If db location changes you update just one file machine.config, instead of going to each application's config file.如果数据库位置发生变化,您只需更新一个文件 machine.config,而不是转到每个应用程序的配置文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在仅更改一个位置的地方设置连接字符串? - how do I setup the Connection String where I only change it one place? 我应该在哪里为我的类库添加连接字符串以及如何访问它们? - Where should I put my connection strings for my class library and how do I access them? 我为什么要使用连接池? - Why should I use connection pooling? C#应该在连接池中保持打开连接 - C# should I keep open connection in connection pooling 我在哪里粘贴我的天蓝色连接字符串 - Where do I stick my azure connection string 我应该在控制器中打开数据库连接吗? - Should I be opening a database connection in my controllers? 如何将自己的数据库与连接字符串中的(local)\\ netsdk关联? - How do I associate my own database with (local)\netsdk in the connection string? Visual Studio安装 - 安装后应该在哪里指向本地数据库连接字符串? - Visual Studio Install - Post-install where should I point local database connection string? 我应该在哪里存储我的 ASP.NET Core 应用程序生产环境的连接字符串? - Where should I store the connection string for the production environment of my ASP.NET Core app? 如何在azure中为我的Web应用程序设置连接字符串? - how do i set the connection string for my web application in azure?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM