Click here to Skip to main content
16,021,041 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Example 1

public class foo() 
{
   public void InsertDatabase() 
   {
      using (SQLConnection conn=new SQLConnection("connection info")) 
      {
         conn.Open()
         conn.CommandText="Insert into database";
         conn.ExecuteNonQuery();
      }
   }
}

public void main()
{
   foo f= new foo();
   foo.InsertDatabase();
}


OR

Example 2


public class foo():Idisposable
{
   private SQLConnection sql=new SQLConnection();

   public void OpenDB()
   {
     sql.Open(); 
   }

   public void InsertDatabase()
   {
     sql.commandtext="Insert into database";
     sql.executenonquery();
   }

//Idisposable methods would go here

}

public void main()
{
    using (foo f= new foo()) 
    {
       foo.OpenDB();
       foo.InsertDatbase();
    }
}


You can see the two examples, one would have open in the InsertDatabase method and the other would have an open method and then the InsertDatabase method. I realize with connection pooling opening and closing isnt really an issue, but what is the best practice way to do this. Most people online tend to lean toward example 1, but is this right?
Posted

There is no best practice on this. It's more amatter of style and project requirements. Someones I do it like your first example. Sometimes the other way. But I DO always put a try/catch block around db access stuff.
 
Share this answer
 
Try this code for Open Connection...

C#
public void InsertDatabase()
   {
try
{      
using (SQLConnection conn=new SQLConnection("connection info"))
      {
         conn.Open();
         conn.CommandText="Insert into database";
         conn.ExecuteNonQuery();
      }
}
catch(exception ex)
{
messagebox.show(ex.tostring());
}
finally
{
conn.close();
}
   }
 
Share this answer
 
v2
When you write methods, then name of the method should give a clear indication of what the method does, and nothing more. So I would lean towards your second example because InsertDatabase should only insert into a database. OpenDB is short and sweet, but if you want to wrap some generic validation around it, you will only have to do it once in that method, so it is a win win. Neither is wrong, however. If you have other project source to look at where you work, you could look at those and write yours to be consistent with those.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900