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.
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");
Yes, you will have to dispose (of) the connection separately. You can also see this in the source code: SqlCommand.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With