how to connect sql server in C# | SQL Server Connection

SQL Server Connection

We always use Connection String in forms that we design but when you design a big software you should set the connection string for once and use it in many forms. In this method you use the name of the Connection String instead of the connection string text.
Every time you want to change the connection string just change the main connection string in the  

App.Config file.

By this method you don't need to change all of the forms in your project, just change the Connection String in the App.Config.

Using the Code

First of all you should set the connection string in the App.Config file. For example I set the connection string for my database as you see here:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
         <add name="CharityManagement" connectionString="Data Source=.;Initial Catalog=CharityManagement;Integrated Security=True"/>
    </connectionStrings>
</configuration>

After that you use the connection string in your forms using this code:
using System; 
using System.Configuration;  
using System.Data;  
using System.Data.SqlClient; 
using System.Windows.Forms;
Then you can get the Connection String from
the App.Config by using the ConnectionStrings property.

You can use this method in both Windows Forms and ASP.NET projects.

using System;
using System.Configuration;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
        class Program
    {
        static void Main(string[] args)
        {
            ReadProducts();
        }
        static void ReadProducts()
        {
        var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;
        string queryString = "SELECT Id, ProductName FROM dbo.Products;";
        using (var connection = new SqlConnection(connectionString))
            {
             var command = new SqlCommand(queryString, connection);
             connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
                    }
                }
            }
        }
    }
} 

XML

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <connectionStrings>
        <add name="WingtipToys"  connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
    </connectionStrings>
</configuration>

Post a Comment

0 Comments