Connection question

fkheng

Well-known member
Joined
May 8, 2003
Messages
155
Location
Malaysia
is it proper to reuse a same oledbconnection over and over again, being defined in a main module so that it can be shared by forms which need it at a particular time? instead of creating new connection objects all over? are there a ny issues involved here?
 
In my program I create the SqlConnection in the main start up program, then reference it in various forms where needed.

Heres an example;

C#:
// Main form.
private SqlConnection m_con;
private SomeForm m_frm;

// Main forms constructor.
m_con = new SqlConnection(); // You get the idea..
m_frm.Connection = m_con; // Reference connection where needed.

// SomeForm.
SqlConnection m_con;
public SqlConnection Connection {
   get {
      return m_con;
   }
   set {
      m_con = value;
   }
}

I use this for custom controls, etc too..
 
i see, hm......so ure reusing the connection for various other forms

wat if i do not reuse it, but create new connections for each form, would that affect the efficiency of the program? or any issues here?
 
You could if you wanted to, but what if later you wanted to change the connection string for some reason? Youd then have to change all the connection strings in all your forms, then retest them all to make sure they work. Youd also have to do tests to insure that all connections were closed when your app closes.

Referencing an object is a bit faster then creating a whole new one, not to mention it saves a little bit of memory. But who really cares about that in this day and age? You can really just do what you want. Its your program and your design, Im just tossing out possible problems that it may cause later.

Using a single module (as your first post mentions) to provide a public property for your connection is also a valid choice, as is Robbys suggestion of putting it inside a class too (which makes more sense for .NET).

Bottom line is, do what you want. Just try and make a good decision and think ahead so your programs are easy to update at a later date. All I was doing was offering an alternative, and to be honest Robbys suggestion is probably better then mine. I originally misread the initial post which is why I offered an addition suggestion.
 
i see, er......how would it differ if i placed the connection in the class not in the module? how do i use it then? any difference in syntax or writing the codes to use the connection from the class?
 
Back
Top