Sql connection helper

Hi everyone,

This is my first post here, so I will start with an very simple and quite useful example of the SQL connection object helper. When using ado.net it basically helps reducing amount of code needed to instantiate connection.

public class Connection
{
    public Connection()
    {

    }

    public static SqlConnection Current
    {
        get
        {
            SqlConnection con = null;
            if (HttpContext.Current.Session["sqlconnection"] == null)
            {
                HttpContext.Current.Session["sqlconnection"] = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
            }
            con = (SqlConnection)HttpContext.Current.Session["sqlconnection"];
            if (con.State != ConnectionState.Open) { con.Open(); }
            return con;
        }

    }
}

All you need to do is to use Current property of that object to create connection instance or reuse it if already created eg.

    using (SqlCommand cmd = new SqlCommand("getData", Connection.Current))
    {
           cmd.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
               while (reader.Read())
               {
                   //to do get data
               }
            }
     }

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...