blog

Home / DeveloperSection / Blogs / Database connectivity in C#

Database connectivity in C#

AVADHESH PATEL4686 12-Mar-2013

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

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


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)
        con.Open();
        var cmd = new SqlCommand("select * from EmpInfo", con);
        // put your code here
        if (con.State == ConnectionState.Open)
                    con.Close();
       }
  }


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


Updated 18-Sep-2014
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By