A Closer Look at ADO.NET: The Connection Object - Common Errors While Connecting
(Page 4 of 5 )
Although the code to establish a connection to the database is simple, many problems can happen. For example, the server doesn't exist or the database doesn't exist, which cause us problems when running the code. For this reason we will use the try/catch/finally statement to catch the exception and print the exception message to the console window. Here is what the code looks like:
using System;
// reference to the namespace that contains most
// of the classes that form the ADO.NET Architecture
using System.Data;
// referene to the namespace of the SQL Server .NET Data provider
using System.Data.SqlClient;
namespace AdoApp
{
class Class1
{
static void Main(string[] args)
{
SqlConnection SqlConn1 = new SqlConnection();
SqlConn1.ConnectionString = "Server=(local);Database=pubs;User ID=sa;Password=;";
try
{
// We use the Open() method to establish the connection
SqlConn1.Open();
SqlCommand SqlComm1 = new SqlCommand();
SqlComm1.Connection = SqlConn1;
SqlComm1.CommandText = "Select * from titles";
SqlDataReader SqlReader = SqlComm1.ExecuteReader();
while(SqlReader.Read())
{
Console.Write(SqlReader["title_id"]);
Console.Write("--");
Console.Write(SqlReader["title"]);
Console.WriteLine();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// here we call the Close() method to close the Connection
SqlConn1.Close();
Console.ReadLine();
}
}
}
}
Now stop the SQL Server, then run the code, and you will get the next exception message printed to the console window after 15 seconds.

In the Connection String, modify the database name from pubs to pub and run the application again.

As you can see, the try/catch/finally statement is good to use with the connection object. Note that we close the connection object in the finally block.
Next: Using VS.NET to Create a SqlConnection Object >>
More Database Code Articles
More By Michael Youssef