Instructor-led online courses in ASP.NET Core, ASP.NET MVC, and ASP.NET Design Patterns. Read more...
Live instructor-led online courses in ASP.NET Core and Design Patterns. Registration is open for December 2018 batch. More details are available here.

<%@ Page %>

ADO.NET Series - Connecting with a Database


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
//add StateChange event handler
cnn.StateChange += 
new StateChangeEventHandler(s1.OnStateChange);
("Press any key to open 
database connection...");
//open connection
("Press any key to close 
database connection...");			
//close connection
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)
("State changed from " + 
e.OriginalState + " to " + 
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.


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 a software consultant, trainer, author and spiritual yoga mentor having 23+ years of experience in software development. He teaches online training courses in ASP.NET Core, Angular, and Design Patterns to individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 26 April 2003

Tags : ADO.NET Data Access SQL Server

Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.