Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make central SqlConnection

Tags:

c#

sql

sql-server

I have wondered what is the best way to make one central SqlConnection. So first thing when I started programming in C# was to put SqlConnection like this into each form I made:

public partial class form1 : Form
{
    SqlConnection conn = new SqlConnection(
"Data Source=SERVER\\SQL;Initial Catalog=DataBase;User ID=user;Password=pass");

    public form1 ()
    {
        InitializeComponent();
        timer1.Start();
    }
   }

Now I would like to make one central connection and get rid of all of these codes in beggining of each form.

I thought that class would be best way to do that. So I wanted to ask you if there is another good method how to make that.

As I'm begginer, please excuse my level of description.

Thank you for your answer/comments/opinions.

like image 972
Blaze M Avatar asked Jul 24 '13 12:07

Blaze M


People also ask

How can create a SqlConnection?

Creating a SqlConnection Object A SqlConnection is an object, just like any other C# object. Most of the time, you just declare and instantiate the SqlConnection all at the same time, as shown below: SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

Is it necessary to dispose SqlConnection as well as SqlCommand?

Yes, you will have to dispose (of) the connection separately. You can also see this in the source code: SqlCommand.

Does disposing SqlConnection close connection?

If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose . Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes , the underlying connection is returned back to the connection pool.


1 Answers

The standard way to store SqlConnection information is to use a configuration file such as app.config or web.config. Alternatively, you may create your own configuration file.

After that, use ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString rather than the hardcoded connection settings

like image 69
wes Avatar answered Sep 24 '22 16:09

wes