i

ASP.Net A Complete Guide

Connections

Ado.net provides the facility to connect to the database by using the SQL classes. Connections give the entry point for the data source so that we can retrieve the data from the database.

Below are two mostly used namespace for the database:

  • Connection object for SQL Server (SqlConnection): -(System.Data.SqlClient).

  • Connection object for ORACLE (OracleConnection):- (System.Data.OracleClient).

SQLConnection Syntax:

SqlConnection connection = new SqlConnection("Connection string") 

Example:

using System; 

using System.Data.SqlClient; 

namespace AdoNetconnectionsoleApplication 

    class ConnectionProgram 

    { 

        static void Main(string[] args) 

        { 

            new ConnectionProgram().connectionnecting(); 

        } 

        public void connectionnecting() 

        { 

            Sqlconnectionnection connection = null; 

            try 

            { 

                connection = new Sqlconnectionnection("data source=.; database=student; integrated security=SSPI"); 

                connection.Open(); 

                connectionsole.WriteLine("connection Established Successfully"); 

            } 

            catch (Exception e) 

            { 

                connectionsole.WriteLine("Something went wrong\n"+e); 

            } 

            finally 

            {   // Closing the connection 

                connection.Close(); 

            } 

        } 

    } 

SqlConnection Constructors:

  • SqlConnection(): Used to initializes the new instance.

  • SqlConnection(String): Used to initialize a new instance and takes connection string as a parameter.

SqlConnection Methods:

  • Open() : It open a database connection.

  • BeginTransaction() : It start the database transaction

  • Close(): It closes the connection to the database.