How to set SQL Server connection string in ASP.Net?

Firstly;

 .NET DataProvider -- Standard Connection with username and password:

Put this at the top of your code:

using System.Data.SqlClient;

Put this  in your code body:

SqlConnection conn = new SqlConnection();

conn.ConnectionString =

"Data Source=ServerName;" +

"Initial Catalog=DataBaseName;" +

"User id=UserName;" +

"Password=UserPassword;";

conn.Open();

Secondly;

 .NET DataProvider -- Trusted Connection:

Put this at the top of your code:

using System.Data.SqlClient;

Put this  in your code body:

SqlConnection conn = new SqlConnection();

conn.ConnectionString =

"Data Source=ServerName;" +

"Initial Catalog=DataBaseName;" +

"Integrated Security=SSPI;";

conn.Open();

Thirdly;

.NET Configuration manager (Web configuration);

Put this at the top of your code:

using System.Web.Configuration;

using System.Data.SqlClient;

Put this in Web.Config:

<connectionStrings >

<add name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"

providerName="System.Data.SqlClient"/>

</connectionStrings>

and where you want to setup the connection variable in your code body:

SqlConnection conn = new SqlConnection( WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

You can also use external configuration file to specify connection strings section, and refer that file in application configuration file like in web.config file:

<configuration>

<connectionStrings configSource="connections.config"/>

</configuration>

The external configuration connections.config file will contain connections section:

<connectionStrings>

<add name="Name" providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />

</connectionStrings>

Just so you know, modifying contents of external configuration file will not restart the application (as ASP.net does by default with any change in application configuration files.)

Before I go. It is a good practice to store the connection string for your application in a config file. Oh! Are you CURIOUS ? Check out more about store connection string in web.config between versions of .NET.

More tips coming up. Try it out.

Comments

Popular posts from this blog

AWS: Benefits of using Amazon S3

Google To Acquire Looker For $2.6 Billion

Python - GUI - Tkinter(Bar & Pie Chart)