Storing connection in a static class (ASP.NET)
asp.net, class, database, static
Solution
It is better not to store the connection in a static field. Create the connection object on demand and let the connection pooling manage your connections.
Problem
Since I'm using Postgresql and can't use LINQ to SQL, I wrote my own wrapper classes. This is a part of the Student class: ``` public class Student : User { private static NpgsqlConnection connection = null; private const string TABLE_NAME = "students"; public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Password { get; set; } /// <summary> /// Reads data from the data reader and moves it to the Student class. /// </summary> private static void ReadFields(Student student, NpgsqlDataReader dr) { student.Id = Int32.Parse(dr["id"].ToString()); student.FirstName = dr["first_name"].ToString(); student.LastName = dr["last_name"].ToString(); student.Password = dr["password"].ToString(); } /// <summary> /// Updates the student /// </summary> public void Update() { Connect(); Run(String.Format("UPDATE " + TABLE_NAME + " SET first_name='{0}', last_name='{1}', password='{2}' WHERE id={3}", FirstName, LastName, Password, Id)); connection.Dispose(); } /// <summary> /// Inserts a new student /// </summary> public void Insert() { Connect(); Run(String.Format("INSERT INTO " + TABLE_NAME + " (first_name, last_name, password) VALUES ('{0}', '{1}', '{2}')",FirstName, LastName, Password)); connection.Dispose(); } private static void Run(string queryString) { NpgsqlCommand cmd = new NpgsqlCommand(queryString, connection); cmd.ExecuteScalar(); cmd.Dispose(); } private static void Connect() { connection = new NpgsqlConnection(String.Format("Server=localhost;Database=db;Uid=uid;Password=pass;pooling=false")); connection.Open(); } //.... ``` So as you see with every INSERT, DELETE, UPDATE request I'm using Connect() method which connects to the database. I didn't realize how stupid it was before I had to wait for 10 minutes to have 500 rows inserted, as there were 500 connections to the database. So I decided to move Connection property to a static DB class. ``` public static class DB { private static NpgsqlConnection connection = null; public static NpgsqlConnection Connection { get { if (connection == null) { connection = new NpgsqlConnection(String.Format("Server=localhost;Database=db;Uid=uid;Password=pass;pooling=false")); connection.Open(); } return connection; } } public static void Run(string queryString) { NpgsqlCommand cmd = new NpgsqlCommand(queryString, connection); cmd.ExecuteScalar(); cmd.Dispose(); } } ``` It works now! I replaces all `Run` methods in the Student class with `DB.Run` But I want to know if it will work fine with a lot of people online, not me only. I'm not sure how static things work with ASP.NET, maybe it'll eat a lot of memory?..