Home > DeveloperSection > Blogs > Database connectivity in C#

Database connectivity in C#

C# C# 
0 Comment(s)
 2228  View(s)
Rate this:

Database connectivity in C#

In this blog, I’m going to describe how to establish connection with database in C#. There are very easy steps, using that you can get data from your database. In C# for database connectivity, C# provides app.Config file.
Database connectivity steps are given below.

Step 1: Open your windows application.

Step 2: Go to solution explorer and add “Application Configuration File”. After that you see “App.Config” file are added into your project.

Step 3: Now open “App.Config” file and write below code into <configuration> tag



    <add key="dbconnection" value="data source=.;initial catalog=Demo;integrated security=yes;"/>



Step 4: Now, open your .cs page where you access database. For establishing connection,   System.Configuration namespace is required, hence go to solution explorer and check System.Configuration.dll file’s reference is added in your project or not. If it is added that’s good. If not then add reference through right click on References in solution explorer and select Add Reference… option. Then select .Net tag and choose System.Configuration or System.Configuration.dll file.

Step 5: Come back on your .cs page and include below namespaces.

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

Step 6: Now go to your event blog where you put connection. For demonstration I have define connection into Form1_Load() block as below.

private void Form1_Load(object sender, EventArgs e)


   using (var con = new SqlConnection(ConfigurationManager.AppSettings["dbconnection"]))


       if (con.State == ConnectionState.Closed)


        var cmd = new SqlCommand("select * from EmpInfo", con);

        // put your code here

        if (con.State == ConnectionState.Open)




This blog is completed here. I hope you enjoy this.

Don't want to miss updates? Please click the below button!

Follow MindStick