0

I have a question regarding where to place the code for the db-connection in the program. I have a smart device app and I'm establishing every time a db-conn before a query and closing it after the query is finished.

I have the feeling that to establish a connection it takes a certain time. Wouldnt it be better to establish the connection in On Form_Load or so and just look up whether its still open before querying?

What would you advise?

Regards

  • Yes, open the connection on load and close it on exit. Keep in mind that some servers timeout the connection if you haven't queried anything in a while, so you need to make sure it's alive before you do anything. – Daniel Aug 13 '14 at 07:28
  • Sounds plausible - thank a lot. – chesterluck Aug 13 '14 at 07:41
  • It is best to instanciate your object in formload or in your constructor, but Open the connection just before accessing your db and close it right after. do not let a connection to db open. – Nadeem_MK Aug 13 '14 at 09:34
  • right now it is implemented like this. But it takes time to establlish a connection and the application has to be fast :) – chesterluck Aug 13 '14 at 09:53
  • What server are you using for database? – Hoh Aug 13 '14 at 12:15

1 Answers1

0

You can put code that establishes db connection in method like GetConnection as mentioned in below approach.

Approach-1

  1. You can create wrapper class which should have methods like GetConnection,ExecuteQuery,ExecuteNonQuery,ExecuteStoreProcedure(or simply CxecuteCommand).
  2. Declare one global object of wrapper class type created in above step in your class where you want to use it.
  3. Initialize this object inside the method whereever you want to use it.
  4. Access the required method of wrapper class as per your need.
  5. Implement the Dispose method from IDisposable Interface to serve memomry management with the help of Garbage collection.

Approach-2

  1. You can create wrapper class which should have methods like GetConnection,ExecuteQuery,ExecuteNonQuery,ExecuteStoreProcedure(or simply CxecuteCommand).
  2. In your form.cs, if all methods/events requires some or other sql command then its better to initialize the object if wrapper class globally or in constructor.
vipin
  • 1
  • 6