ok..you'd always have to open and close your connections everytime you use them..but if you want to implement the write-once-run-everywhere style..then fortunately .NET come's with the
ref
keyword to help you..so what you can do is this..
1. create a class and put in a method for connecting to the database..example
.
.
static class DB
{
public static void connectDB(ref SqlConnection conn, ref SqlCommand cmd)
{
conn = new SqlConnection();
conn.ConnectionString="[input connection string here]";
cmd.Connection=conn;
cmd.CommandType=CommandType.StoredProcedure;
}
}
So all you just have to do is to call this method inside the classes you want to use it, and it will do all the above for you without you re-typing them everytime..
Example if I want to use it in a different class named
useHere
, I would do this..
.
.
class useHere
{
SqlConnection conn;
SqlCommand cmd;
public void addData(ref conn, ref cmd)
{
DB.connectDB(conn,cmd);
cmd.CommandText="[input stored proc. name here]";
conn.Open();
cmd.ExecuteNonQuery();
if(conn.State == ConnectionState.Open)
{
conn.Close();
}
cmd.Dispose();
}
and you're game.. :) . If you like it, accept answer and VOTE!