How to connect .NET with sql database?


You can connect your .Net application to SQL Server using .Net framework data provider for SQL server i.e System.Data.SqlClient.

Add Namespace

using System.Data.SqlClient;

Sql Server connection string

connectionString="Data Source=ServerName; Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

Data Source=ServerName;

ServerName: Your SQL Server Name.

Initial Catalog=DatabaseName;

DatabaseName: SQL Server Database that you would like to connect.

User ID=UserName;

UserName: SQL Server user name

Password=Password

Password: SQL Server password

A Sample C# code to connect SQL Server using connection string.

string connectionString = null;#break connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";#break SqlConnection con = new SqlConnection(connectionString);#break try#break {#break con.Open();#break MessageBox.Show("Connection Open ! ");#break con.Close();#break }#break catch (Exception ex)#break {#break MessageBox.Show("Can not open connection ! ");#break }#break

con.Open(): Is used to open the database connection.

con.Close(): Is used to close the connection.

You can also add your connection string in web.config file. It's always a good practice to add connection string in web.config file instead of hardcoding it in code. The <connectionStrings> section you have to add inside <configuration> section.

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" />
</connectionStrings>

To get the connection string from web.config

Add the namespace System.Configuration, then using ConfigurationManager you can get the connection string as shown below.

using System.Configuration; #break #break string connetionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

Here "ConnectionString" is the name of the connection that we added in the <connectionStrings> section.

Share On