Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to connect to database

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 275
    Comment on it

    We can connect our C# application to data in a SQL Server database by using following ways:

    1. First Method

    Firstly, we need a connection string to connect to database.This connection string contain the information about the server to which we are going to connect.

    SQL Connection string

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

    Add the following namespace in your code:
    using System;
    using System.Windows.Forms;
    using System.Data.SqlClient;

    Now, we have to create an instance of the SqlConnection and pass the Connection String as an argument in it.

    using ( SqlConnection connection = new SqlConnection( connetionString ))
     {
        connection.Open();    
        
    }

     

    A Sample C# program that connect SQL Server using connection string.

    using System; 
    using System.Windows.Forms; 
    using System.Data.SqlClient; 
    namespace ConnectToDatabase
    { 
        public partial class FormSample : Form 
      {
          InitializeComponent(); 
      }
    
    private void button_Click1(object sender, EventArgs e) 
    {
      string conString = "Data Source=(local); Initial Catalog=EmployeeData;Integrated Security=True";
    try 
    {
       using ( SqlConnection connection = new SqlConnection( conString ))
       {
           connection.Open();        
     }
    }
    catch (Exception ex) 
     { 
        thrown ex
     }
    }

    2. Second method

    We can also connect to SQL Server database by providing a connection string in Web.config file.

    To configure a connection string for SQL Server in the Web.config file use the following steps:

    1. Create or open the Web.config file of an application.

    2. Define a ConnectionStrings element in Configuration tag. In this tag, create an add tag which define the following properties:

    • name  

          It define the value to the name which is use to give a reference to the connection string.

      Example:-

      name="EmpDataConnectionString"

    • connectionString  

           It define a connection string.

      Example:

      connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=(local)"

    •  providerName:-

                  It define the value "System.Data.SqlClient" which specifies that use the ADO.NET provider.

    <connectionStrings>

        <add name="EmpDataConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=(local)" providerName="System.Data.SqlClient" />

    </connectionStrings>

    4. At the end save the Web.config file and close it.  

    Add the following namespace in your code:

    using System.Configuration;

    using System.Data

    To read the connection string use the ConfigurationManager class.

    Example:

    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

    A Sample C# program that connect SQL Server using connection string.

    using System.Configuration;
    using System.Data;
    
    using System.Configuration;
    using System.Data;
    
    namespace ConnectToDatabase
    { 
        public partial class FormSample : Form 
    {
    InitializeComponent(); 
    }
    
    private void button2_Click(object sender, EventArgs e) 
    {
       try 
       {
             using ( SqlConnection connection = new SqlConnection( ConfigurationManager.ConnectionStrings["EmpDataConnectionString"].ToString() ))
           {
               connection.Open();     
        }
    }
     catch (Exception ex) 
     { 
        thrown ex
     }
    }

    3. Third method

    To connect to database we use an App.Config file in which we define a connection string.

    For example:

    <configuration>

     <connectionStrings>

       <add name="EmpConString" connectionString="Data Source=(local);Initial Catalog=EmpRecord;Integrated Security=True"/>

     </connectionStrings>

    </configuration>

    In C# Code

    Add the following references

    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;

    Then, to read the Connection String value from the App.Config file use the below code:

    string connectionString = ConfigurationManager.ConnectionStrings["EmpConString"].ConnectionString;

     

    A Sample C# program that connect SQL Server using connection string.

    <configuration>
    
    <appSettings>
    
    <add key="ConnectionString" value="Data Source=MY-PC;Initial Catalog=DBA;User ID=sa;Password=MYSQL123@" />
    
    </appSettings>
    
    </configuration>

     

    using System.Configuration;
    using System.Data.SqlClient;
    
    namespace ConnectToDatabaseSample
    {
    public partial class EmpRecord : Form
    {
       SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
    
        public CommodityEdit()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
               MyConnection.Open();
            }
            catch (Exception)
            {
               throw;
            }
         }
      }
    }

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: