Skip to main content

ADO.NET Connection string


ADO.NET Connection string Explained

Connection String is a normal String representation which contains Database connection information to establish connection between Database and your Application. The Connection String includes parameters such as the name of the driver, Server name and Database name, as well as security information such as user name and password. Read more from connection string site here

Usually Data Providers use a connection string containing a collection of parameters to establish connection with the database through applications. The .NET Framework provides mainly three data providers, they are:
  • Microsoft SQL Server
  • OLEDB
  • ODBC
We will be looking at how to make a connection string to the above ADO.NET Data Providers.

Microsoft SQL Server Connection String
connetionString="Data Source=ServerName;Initial Catalog=Databasename;
User ID=UserName;Password=Password"

OLEDB Data Provider Connection String
connetionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;"

ODBC Connection String
connetionString="Driver={Microsoft Access Driver (*.mdb)};
DBQ=yourdatabasename.mdb;"

You have to provide the necessary connection information to the Connection String attributes.

We will looking at how to use these ADO.NET Data Providers to establish connection to the Data Source through C# language.

C# SQL Server Connection

You can connect your C# application to data in a SQL Server database using the .NET Framework Data Provider for SQL Server. The first step in a C# application is to create an instance of the Server object and to establish its connection to an instance of Microsoft SQL Server.

The SqlConnection Object is handling the part of physical communication between the C# application and the SQL Server Database. An instance of the SqlConnection class in C# supports the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement.

Sql Server connection string

connetionString="Data Source=ServerName;
InitialCatalog=DatabaseName;User ID=UserName;Password=Password"

If you have a named instance of SQL Server, you'll need to add that as well.
"Server=localhost\sqlexpress"

When the connection is established, SQL Commands will execute with the help of the Connection Object and retrieve or manipulate the data in the database. Once the Database activities is over, Connection should be closed and release the Data Source resources.

 The Close() method

The Close() method in SqlConnection Class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the SQL Server Database.

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


Connection string from web.Config

<add name="DefaultConnection" connectionString="Data Source=DESKTOP-EIRHPII;Initial Catalog=csharpnaija_employees;Integrated Security=True" providerName="System.Data.SqlClient" />

Connection to Db test method
using System;
using System.Data.SqlClient;

namespace DatabaseFirstApproach.Models
{
     public static class CsharpnaijaUtility
    {
        public static bool ConnectToDb(string connectString)
        {
                try
                {

                     bool isConnected = false;
                     using(var conn = new SqlConnection(connectString))
                     {
                           conn.Open();

                           if (conn.State==System.Data.ConnectionState.Open)
                           {
                                isConnected = true;
                           }
                     }
                     return isConnected;
                }
                catch (Exception ex)
                {

                     throw ex;
                }
        }
    }
}

Action method in Employee Controller that verified if database connection is established
 public ActionResult Connect()
        {
 var connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            var isconnected = CsharpnaijaUtility.ConnectToDb(connString);
            if (isconnected)
            {
                ViewBag.Connected = "Connected to the Database";
            }
            else
            {
                ViewBag.Connected = "Not Connected to the Database";
            }
            return View();
        }

Connect via an IP address

connetionString="Data Source=IP_ADDRESS,PORT;
Network Library=DBMSSOCN;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"
1433 is the default port for SQL Server.

Trusted Connection from a CE device

connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=SSPI;
User ID=myDomain\UserName;Password=Password;
This will only work on a CE device

Connecting to SQL Server using windows authentication
"Server= localhost; Database= employeedetails;
Integrated Security=SSPI;"

Store Connection String in Web.config

It is a good practice to store the connection string for your application in a config file rather than a hard coded string in your code. The examples of connection string in web.Config or app.config.

Connection string in .NET config file

Do not use the appSettings section in web.config. Instead use the connectionStrings section in web.config.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
</configuration>

To read the connection string into your code, use the ConfigurationManager class.
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

Remember to add a reference to the System.Configuration component. Then include the namespace System.Configuration to get access to the ConfigurationManager class.

// C# using System.Configuration;
Clear connection strings coming from higher level config files

Configuration files are hierarchical, with machine.config being at the highest level. You can clear connection strings defined earlier in the hierarchy to make sure any unwanted settings don't bubble down to your desired value.


<?xml version="1.0" encoding="utf-8"?>
 <configuration>
 <connectionStrings>
<clear /> <!-- clear all other
connection strings -->
 <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
</configuration>

Adding <clear /> at top in the connectionStrings section is usually a good practice to make sure no other connection strings are bubbling down from a higher level configuration file.


Note

Always store the connection string in a config file. It's not any harder once you get used to it and you will benefit from it as it is much easier to change connection string properties when your application is in production.

Comments

Post a Comment

Popular posts from this blog

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

Interface with real life Examples

Interfaces with real life examples An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a tricyclic class and a truck class. Each of these three classes should have a start engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that  they must  have a start engine action is the domain of the interface. The syntax of an Interface We can implement single interface or multiple interfaces to the class. By default interfaces are public. We declare interface by using "interface" keyword. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsharpnaijaInterfaceTutorial {     interface IEngine     {         void Start();     }...

The Out Parameter with Example in C#

  The Out Parameter with Example in C# In C#,  out  keyword is used to pass arguments to the method as a  reference type . The  out  keyword same as the  ref  keyword but the only difference is  out  doesn’t require a variable to be initialized before we pass it as an argument to the method but the  variable  must be initialized in called method before it returns a value to the calling method. The out parameter in C# is also useful to return more than one value from methods. Declaration of C# Out Parameter Following is a simple example of using  out  parameters in C#.   int x; // No need to initialize variable OutParameterMultTest ( out x ) ;   From the above declaration, we just declared a variable  x  and pass it to the method by using  out  parameter without assigning any value but as discussed, the variable must be initialized in called method before it returns a value...