I have recently been put on an existing project and am trying to reduce the amount of duplicate code.
Right now there are many methods relating to database interaction. The Database connection is opened and closed within each of these methods. Essentially, the exact same code is used in every single method to open and close the connection.
public static void AddToTable()
{
DbConnection con = Common.CreateConnection();
DbCommand cmd = con.CreateCommand();
//cmd.CommandText = SQL COMMAND GOES HERE
//cmd.ExecuteNonQuery();
con.Close();
}
I understand the importance of opening and closing the connection but seeing these exact same lines of code in every method smells funny to me.
Does C# have some kind of way I could accomplish automatically creating the connection (in this case the con and cmd variables) when the method is started and then closing the connection when the method is finished?
usingstatement.