howto make a connection to database available in my classes.

D

Digital Fart

howto make a connection to database available in my classes.

What is the best practice when i want to write classes
that need a connection to the database?

Do i make a conn variable in my main() and give
it as a parameter to every object i make that needs
access to the database

ex.

A class called Price that need to do
some bussines logic to a database.

Price price = new price(param,param,connection)

or do i connect to the database in every class
i build

ex.

A class called Price that does a connection itself.

Price price = new price(param,param)

or any better practice?
 
B

Bob Powell [MVP]

Re-create the connection as-needed from a constant connection string and
allow connection pooling that's built in to the system to manage this for
you.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
J

John Richardson

another good spot is the App.Config file which allows for different conn
strings for different users... Enterprise Library uses this, I think.
 
J

John Richardson

I think that's a best practice across most languages now (opening and
closing the conn).
Stick it in a using block though, to guarantee the conn closes... that way
if you error out in your code block, the conn is guaranteed to close. I
think that code is a poor example because they omitted that. If (when) you
use the VS designer, you can stick the conn string in the App.config file
using the "(DynamicProperties)" section in the properties window, if you
have added the SqlConnection object to your form through the designer
(through the server explorer). VS handles it for you. Or you can add it
manually, of course.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top