Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Which would be a better style in terms of handling the connections in c sharp

function A()
{
SqlConnection connString = new SqlConnection(SqlCred);
            SqlCommand cmdInsert = new SqlCommand("Query here", connString);
     try
          {
            connString.Open();
            cmdInsert.ExecuteNonQuery();
            connString.Close();
            connString.Dispose();
          }
    catch
          {}

}


function B()
{
using(SqlConnection connString = new SqlConnection(SqlCred))
     {
     using sqlcmd cmd = (//stuff//)
          {
           connString.Open();
           cmd.executenonquery();
          }
     }
}



also while I was playing around with each of these i came across the idea of having a global connString creating only one pool of connections for the functions to open and close accordingly.
namespace Program
{
    public class Program class
    {
     SqlConnection connString = new SqlConnection(SqlCred);
     functionX(connString);
     functionY(connString);
    }

}


assuming function x and y open and close only when they need to use the connString
Posted
Updated 10-May-11 9:14am
v3

1 solution

I'm sorry, but that code resembles nothing I've seen that would compile, and has nothing to to with SQL, so that makes your tags wrong, too.
 
Share this answer
 
Comments
TeddyB777 10-May-11 15:14pm    
they are just snippets. none of it is expected to compile. Just curious about the style. Also forgot to note that this is in C#

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