Closing a conneciton in the “unload” method

前端 未结 5 1056
故里飘歌
故里飘歌 2021-01-18 15:31

I have inherited a web framework whereby the previous developer has opened and closed his database connections in the init/unload methods of the page life cycle. Essentially

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 15:35

    I always make use of using block soemthing as below

    using( SqlConnection)
    {
    
    }
    

    so that it never cause any problem

    if you dont want to write code for opening connection again and again create one class

    public class SqlConnectionManager
    {
        public SqlConnection GetSqlConnectionManager()
        {
           //create and return connection
           //SqlConnection con = new SqlConnection();
           //return con;
         }
    
    }
    

    In You class files

    SqlConnection conn = null;
    using (conn = (new SqlConnectionManager()).GetSqlConnectionManager())
    {
         //do work with connection
    }
    

    So by the above way you do not need to write code again and again and there is also no need to write code to close connection because its automatically get dispose by using block.

提交回复
热议问题