Friday, November 28, 2014

ASP.Net handle database connection


When you are not closing the connection correctly. This lead to following error
System.InvalidOperationException Timeout expired. 
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.
Today era is fast and completion is so tuff .so programmer does the coding fast. In that case we have forgotten to close connection. But my advice to do the quality work.  So here is example to use database connection
1)First use the try catch to handle exception
// Create a new SQL Connection
        SqlConnection conn = new SqlConnection(Utility.Conn);
        try
        {
            // Open the connection to the database
            conn.Open();

            // Create a new SQL Command
            SqlCommand cmd = new SqlCommand("select * FROM user", conn);

            try
            {
                // Execute the command
                cmd.ExecuteNonQuery();
            }
            finally
            {
                // Dispose of the command
                cmd.Dispose();
            }

            // Close the database connection
            conn.Close();
        }
        finally
        {
            // Dispose of the connection object
            conn.Dispose();
        }
1)      Use the using statement. It automatically clean up object whether error occur. So here is example of using statement

using (SqlConnection connNew = new SqlConnection(Utility.Conn))
        {
            // Create a new SQL Command
            using (SqlCommand cmd = new SqlCommand("select * FROM user", connNew))
            {
                // Open the connection to the database
                conn.Open();

                // Execute the command
                cmd.ExecuteNonQuery();

                // Close the connection to the database
                conn.Close();
            }
        }
Simply you have use sql helper library and Microsoft application library. These libraries are very good fast development and quality work

No comments:

Post a Comment

http://blogsiteslist.com