Skip to main content

How To Create Connection With Database in SQL Server

How To Create Connection With Database in SQL Server


Creating and Managing Connections
To connect to a database for retrieving the data and updating the database, performs the following tasks.

1.    Create a connection object
2.    Create a command object
3.    Open the Connection object,
4.    Execute SQL statements in command object
5.    Close the connection object


Creating a CONNECTION object:
The connection component of a data providers is used to establish a connection with a Data Source.


To create a connection between User Interface and Data Source, Create a connection object.

Read: Connected and Disconnected Architecture of ADO.NET

Use SqlConnection class to open the connection of Microsoft SQL Server Database.

After creating the connection object, Use ConnectionString property provides the information that defines a connection to a database by using a string of a parameter.

SqlConnection connection = new SqlConnection();
conncetion.ConnectionString = “DataSource = SQLServer1”;
Initial Catalog = HR; UserID = sa; password : #1234”;

If UserID and Password parameters of connection string is used then Integrated Security parameter is used with Connection String property.

For SqlConnection class, A System.Data.SqlClient namespace should be included. It is a collection of classes used to access a SQL Server Database.


Creating a Command object:
To execute SQL statements, create an instance of SqlCommand class in System.Data.SqlClient namespace.

We can execute SQL statements or stored procedure through command objects.

SqlConnection connection = new SqlConnection();
connection.ConnectionString = “DataSource = SQLSERVER; Initial Catalog = HR; UserID = loginID, Password = 1234”;
SqlCommand cmd = new SqlCommand(“Select from TableName”, connection);

Opening the Connection object:

To open the connection, use Open() method. connection.Open();

Execute SQL Statements in Command Object
To execute the query passed in command object use SqlDataReader object. 

It is initialized by calling the ExecuteReader() method of SqlCommand class.

The SqlDataReader object provides the means of reading stream of Rows from a SQL Server Database.

SqlDataReader myReader = cmd.ExecutReader();
The SqlDataReader object provides means of reading stream of rows from a SQL Server Database.
myReader.Read();

Closing the Connection object:

After executing the commands that you want to execute, close the connection by Close() method.
connection.Close();

Final Code to Connect the UI Database

SqlConnection connection = new SqlConnection();
conncetion.ConnectionString = “DataSource = SQLServer1”;
Initial Catalog = HR; UserID = sa; password : #1234”;
SqlCommand cmd = new SqlCommand(“Select from TableName”, connection);
SqlDataReader myReader = cmd.ExecutReader();
myReader.Read();
connection.Close();

Handling Connection Events:

The connection objects have events associated with it that are used to retrieving information message from a DataSource or to determine. If the state of a connection object has changed.

The ConnectionState enumeration of System.Data namespace describe the current state of the connection to a DataSource.

The various members of ConnectionState are :

Broken: The connection to DataSource is broken. It can occur only after the connection has been opened.

Closed: The connection to DataSource is closed.

Connecting : The connction object is connecting to the DataSource.

Executing : The connection object executes a command.

Fetching : The connection object retrieves the data.

Open : The connection to DataSource is opened.

There are two key events for SqlConnection class are: 

StateChange Event:

It occurs, when the state of the connection changes. An arguments of type StateChangeEventArgs contains Data related to particular event. The property of StateChangeEventArgs.

CurrentState : To get the New State of connection

OriginalState : To get the original State of the connection.

Final code:

Connection.StateChange += new StateChangeEventHandler(OnStateChange);
protected static void OnStateChange(Object sender StateChangeEventArgs args)
{
Console.WriteLine(“The connection State has change from {0} to {1}”, args.originalState, args.Current state);
}

InfoMessage Event:
It occurs when an information message or warning is returned from a DataSource

An argument of type SqlInfoMessageEvents Args contains the Data related to that particular event. The property of SqlInfoMessageEventsArgs.
Error:

To get collection of warning sent through server.

Message: To get the full text of error sent from Database.

Source: To get the name of object that is generated the error.

Final Code:
Connection.InfoMessage += new SqlInfoMessageEventHandler(OnInfoMessages)
Protected static void OnInfoMessage(object sender SqlInfoMessageEventArgs args)
{
          Foreach(SqlError err in args.Errors)
          {
Console.WriteLine(“The {0} error has occurred”, err.Message);
}
}

Connection Pooling

Connection Pooling enables DataSource to reuse connection for a user. It also improves application performance and enhances scalability.

The .NET Framework Data Provider for SQL Server provides connection pooling for ADO.NET client application.

When we open a connection, A connection pool is created that associate the pool with the connection string in connection.

Connection Pooling is controlled by certain parameters that are placed into the connection string property of the SqlConnection class.

These parameters are:
Connection TimeOut(Time in Second) : It is the time to wait while a connection in DataSource is attempted.

Min Pool Size:
Minimum number of connection pool.

Max Pool Size:
Maximum no of connection pool.

Pooling:
When true, it cause the request for a new connection to be drawn from pool.
Connection Reset:

When the connection is removed from the pool, the database connection will be reset.

Load Balancing TimeOut, Connection Lifetime:

Maximum time in second that a pooled connection should live. It is useful in load balanced cluster configuration to force a balance between a server that is online and a server that has just started.

Enlist:
When the value of Enlist is true, the connection is automatically enlisted into creation thread’s current transaction context.

Now, if the pooling property is false, then the pooler opens a new connection.

And, if the pooling property is true, then the pooler acquires (the act of gain) a connection from a pool.

To implement connection pooling, follows the rules.

The connectionString and userID must be same for every users or the service that will participate in pool.

Final Code:
SqlConnection connection = new SqlConnection();
Connection.ConnectionString = “DataSource = SQLSERVER ; userID = sa; password=1234; InitialCatalog = HR; connection Timeout = 20; pooling = true”’
Conection.Open();

The System.Data.dll assembles implements the SQL Server .NET Data provider in the System.DataSqlClient namespace.

Comments

Post a Comment

Popular posts from this blog

ADO.NET Framework | Data Binding | Data Table | Data View | Connected and Disconnected Architecture

ADO.NET Framework | Data Binding | Data Table | Data View | Connected and Disconnected Architecture Data Binding Data binding is the ability to bind some elements of a Data Source with the controls of an application. Read : How To Create Connection with Database in SQL Read  :  What is ADO.NET? On the basis of the number of bound, there are two types of binding: Simple Data Binding: Simple Data Binding is the process of binding a control to a single value in DataSet . The DataSet values can be bound to the control by using the properties of the control. Complex Data Binding Complex Data Binding is the process of binding a component (Data Grid View, List Box, and Combo Box) to display multiple values from DataSet .  Complex data binding is the ability to bind a control to more than one record to a data source. The data source property of the control is used to bind the control to a database. Navigation Between Records After binding to...

Data Adapter and Data Set in ADO.NET

Data Adapter and Data Set in ADO.NET Data Adapter : DataAdapter is a part of the connected environment. A DataAdapter is integral to the working of ADO.NET because of data is transferred to and from a database through a DataAdapter . Read  :  How To Create Connection with Database in SQL Read  :  What is ADO.NET? Read   :   D ata Table and Data View in ADO.NET A DataAdapter retrieves data from a database and store into a DataSet . When you make changes to DataSet the changes in the database are actually done by the DataAdapter . The DataAdapter first compares the data in the DataSet with that in the database and then updates the database. DataAdapter that can be configured to connect to a database in visual studio NET. A DataAdapter uses the connection objects SqlConnection , OleDbConnection , OdbcConnection , OracleConnection to communicate with the database. A DataAdapter communicates with a database ...