Connection pooling is a technique used to improve the performance of database connectivity in applications. It allows the reuse of database connections instead of creating a new connection for every request, which can be expensive in terms of time and resources. Here's a sample code in ASP.NET that demonstrates how to use connection pooling:
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConnectionPoolingSample
{
public class DatabaseManager
{
private string connectionString;
private SqlConnection connection;
public DatabaseManager(string connectionString)
{
this.connectionString = connectionString;
this.connection = new SqlConnection(connectionString);
}
public void ExecuteQuery(string query)
{
try
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
// Execute the query
command.ExecuteNonQuery();
}
}
finally
{
// Close the connection when done
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}
public class Program
{
static void Main(string[] args)
{
string connectionString = "YourConnectionString";
string query = "YourQuery";
// Create a database manager instance
DatabaseManager manager = new DatabaseManager(connectionString);
// Execute the query multiple times
for (int i = 0; i < 10; i++)
{
manager.ExecuteQuery(query);
Console.WriteLine($"Query executed {i + 1} times.");
}
Console.ReadLine();
}
}
}
In the above code, the DatabaseManager
class encapsulates the logic for executing a database query. It takes a connection string as a parameter in its constructor and creates a SqlConnection
object based on that connection string. The ExecuteQuery
method opens the connection, executes the query using a SqlCommand
, and then closes the connection.
The Main
method demonstrates how to use the DatabaseManager
class. It creates an instance of the manager with a connection string and a query. It then executes the query multiple times in a loop, simulating a scenario where the same connection is reused for multiple queries.
By using connection pooling, the underlying ADO.NET framework will automatically manage the pool of connections for you. Connections are reused from the pool when needed and returned to the pool after being used. This helps to improve the performance of your application by avoiding the overhead of creating and tearing down connections for each query.
Remember to replace "YourConnectionString" and "YourQuery" with the actual connection string for your database and the query you want to execute, respectively.
Hope this helps you understand how to implement connection pooling in an ASP.NET application!
Comments
Post a Comment