Connect SQL Server in .Net using C#

In this post we are going to create a connection with Microsoft SQL Server using .Net Framework and we would be using C# as our language.

In order to perform SQL related tasks we need to use SqlClient under Data therefore we would add following line in the code window of each form where we will be performing SQL related tasks.

using System.Data.SqlClient;

Next we need to create a connection which we will be using for dealing with SQL Server. There are many methods to do that but what we will be doing is we will create a static connection so that we can use that connection at all the places and any Server related changes can be done at only one place. Other option is to create a connection anywhere as and when required but it adds a problem when you need to modify the server properties.

For windows application we will be doing this in Program.cs file and for web application we will be doing this by creating a new class.

Here we are demonstrating the same for windows application.

In Program.cs file after writing following line at the top section

using System.Data.SqlClient;
Create a static connection variable as follows
public static SqlConnection Conn = new SqlConnection("data source=localhost; integrated security=sspi;initial catalog=database_name");
In the above statement we are creating a static SqlConnection object to hold the connection to Server. We are passing a single argument to the constructor with some properties values as explained below:-

data source=localhost;

This defines the data source to be used. Generally we provide ‘localhost’ or ‘.’ . We can also give the name of the server which can be found in the Server Manager

integrated security=sspi;

Above property tells about the method to be used for authentication. ‘sspi’ tells not to pass the values and go with the windows authentication. It is more secured as username and password is not stored here for creating a connection else we need to provide the same in connection parameter.

initial catalog=database_name;

We need to pass the name of the database with which we want to create a connection, in this argument. These three property values create a connection with the database server.

2 thoughts on “Connect SQL Server in .Net using C#”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.