<%@ Page %>

ADO.NET Series - Connecting with a Database

Introduction

While working with databases the first thing you need to do is to connect with a database. In this part of the series of articles, we will see how to use SqlConnection class to connect with SQL server database.

Sample Code

Following code snippet shows how you can open and close a database connection.
Sample1 s1=new Sample1();
//create a new sql connection
SqlConnection cnn;
cnn=new SqlConnection
(ConfigurationSettings.AppSettings["connstr"]);
//add StateChange event handler
cnn.StateChange += 
new StateChangeEventHandler(s1.OnStateChange);
Console.WriteLine
("Press any key to open 
database connection...");
Console.ReadLine();
//open connection
cnn.Open();
Console.WriteLine
("Press any key to close 
database connection...");			
Console.ReadLine();
//close connection
cnn.Close();
Here, we created an instance of SqlConnection class and pass connection string to it from appSettings section of application configuration file. Next, we add an event handler to the StateChange event. This event gets fired when the connection changes its state from Open to Close and vice a versa.
public void OnStateChange
(object src ,StateChangeEventArgs e)
{
Console.WriteLine
("State changed from " + 
e.OriginalState + " to " + 
e.CurrentState);
}
The event handler simply prints the previous state to the console. We then open the connection using Open() method. We then simply close it by calling Close() method.

Summary

In this part of the series of articles, we saw how to open and close a database connection. We also saw how to detect the state change of the connection. In the next article we will see how to retrieve records from database table using DataReader class.

Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a yoga mentor, meditation teacher, and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his private online courses on ASP.NET and meditation go here and here.

Posted On : 26 April 2003


Tags : ADO.NET Data Access SQL Server