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...

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...