简体   繁体   中英

Pool with MySQL and ASP.NET MVC

I am developing a web application with ASP.NET and MySQL, but I am not using the SqlClient provider.

I read somewhere (I do not remember where) that if I need to establish a connection pool I need to add some lines to file web.config .

To make a connection, defined in each model there is a connection string, something like:

string sqlConnection = 
    "server=localhost; user id=root; password=***; database=test; pooling=true;Min Pool Size=0; Max Pool Size=60;";

And to connect and do query I do the following:

MySqlConnection conection;
conection = new MySqlConnection(sqlConnection);
string query = "SELECT COUNT(*) FROM documents WHERE user_id = ?user_id;
MySqlCommand cmd = new MySqlCommand(query, conection);`

cmd.Connection.Open();
cmd.Prepare();
cmd.Parameters.Add("?user_id", userID);
cmd.ExecuteReader();
...
cmd.Connection.Close();

But I want to open a connection pool and use pooled connections, I do not want to open and close a connection every time.

I put this in the web.config file:

<connectionStrings>
    <remove name="LocalMySqlServer"/>
    <add name="LocalMySqlServer" 
         connectionString="Data Source=localhost; userid=root;  password=***; database=test; Pooling=true; Min Pool Size=50; Max Pool Size=100;"  
         providerName="MySql.Data.MySqlClient"/>
</connectionStrings>

But when I start the development server, I do not see any connections in MySQL Workbench .

This only happens when I call the model and open a connection.

What is the way to have connection pooling at startup time?

I think you're misunderstanding the concept of connection pooling.

Connection pooling is a mechanism provided by the database driver or provider. You still have to ask for a connection but instead of the driver/provider creating a whole new connection each time you create a connection, it maintains a pool of ready made warmed up objects and hands you one of them.

This all happens silently under the covers.

Update:

To consume a connection string from your web.config :

string sqlConnection = 
   ConfigurationManager.ConnectionStrings["LocalMySqlServer"].ConnectionString;

You might have to add a reference to System.Configuration :

在此处输入图片说明

And add a:

using System.Configuration;

To the top of your class file.

That's for a .NET 4.0 project, but the principle is the same with .NET 2.0.

You can try to change Min Pool Size=0 to something larger. This should ensure that always X number of connections are available in the pool.

尝试:

System.Configuration.ConfigurationManager.ConnectionStrings["LocalMySqlServer"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM