Best practice for reusing SqlConnection

后端 未结 5 2029
误落风尘
误落风尘 2021-01-17 09:43

I\'ve come from Java experience and am trying to start with C#. I\'ve read SqlConnection SqlCommand SqlDataReader IDisposable and I can understand that the best practice to

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 10:22

    As VMAtm has said, .net Pools the connections on it's own, so it is perfectly ok to recreate them. As such I generally write a wrapper for the whole process like this one.

            public static void RunWithOpenSqlConnection(string connectionString, Action connectionCallBack)
        {
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connectionString);
                connectionCallBack(conn);
            }
            catch (Exception ex)
            {
                //Log Error Here
            }
            finally
            {
                if (conn != null)
                    conn.Dispose(); //will close the connection
            }
        }
    
        public static void ExecuteSqlDataReader(string connectionString, string sqlCommand, Action readerCallBack)
        {
            RunWithOpenSqlConnection(connectionString, delegate(SqlConnection conn)
            {
                SqlCommand cmd = null;
                SqlDataReader reader = null;
                try
                {
                    cmd = new SqlCommand(sqlCommand, conn);
                    reader = cmd.ExecuteReader();
                    readerCallBack(reader);
                }
                catch (Exception ex)
                {
                    //Log Error Here
                }
                finally
                {
                    if (reader != null)
                        reader.Dispose();
                    if (cmd != null)
                        cmd.Dispose();
                }
            });
        }
    
    //Example calling these
                ExecuteSqlDataReader(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString, "Select EmployeeID FROM Employees;", delegate(SqlDataReader reader)
            {
                List employeeIds = new List();
                if (reader.HasRows)
                {
                    while(reader.Read())
                    {
                        employeeIds.Add((string)reader[0]);
                    }
                }
            });
    

提交回复
热议问题