Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

During the connection with SQL server could be connect with database from the already define connection. i.e

As I have define the under mention connection in a class & use this connection class at all place instead of defining all
Return "server=.\SQLEXPRESS;AttachDbFilename=F:\jatin\sale\jatin_Data.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"

Now my question is could I use this connection in the Dataset or in Crystal report to avoid all connection defination at every place.

KIndly guide me.
Posted

1 solution

yeah..its very possible thanks to re-usability principle of OOP.
.NET has come up with the ref keyword which allows you to do this very thing..I'll put up a code sample in C# which will illustrate the usage of it in relation to your question..

C#
.
.
/* This class contains the Connection String, connection and command object info  */
static class DB_Conn
{
  public static void Connection(ref SqlConnection conn, ref SqlCommand cmd)
  {
    conn = new SqlConnection();
    conn.ConnectionString = "[Input Connection String here]";

    cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandType = CommandType.StoredProcedure; // or Text / Table
  }
}

Now using it in a different class without having to create everything again..

C#
.
.
class UseData
{
  /* Now this next step is very important in order to ensure re-usability 
Declare a connection and command object  */


SqlConnection conn; /* you can set them to null if you want*/
SqlCommand cmd;

/* So to use it in a member method like below..*/

Public void deleteData(ref Conn, ref Cmd)
{
  /*Now just call the method in the 1st class and pass the connection objects in your argument list to it   */

DB_Conn.Connection(Conn,Cmd);
/* and it will set up all the connection and command objects just as was done in the method */

cmd.CommandText="[Input stored Procedure/Query string here]";

conn.Open();
cmd.ExecuteNonQuery();


if(Conn.State == ConnectionState.Open)
{
  Conn.Close();
}

cmd.Dispose();
/* This is optional but for performance reasons and good programming practice, I manually do my garbage collection */

}

}

And your program should run smoothly..
If you love the above, accept answer and give it a vote..:)
 
Share this answer
 
Comments
Dalek Dave 3-Sep-10 10:42am    
Good Answer.

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