Configuring Connections and Connecting to Data in Microsoft .NET Framework 3.5
- 2/25/2009
- Before You Begin
- Lesson 1: Creating and Configuring Connection Objects
- Lesson 2: Connecting to Data Using Connection Objects
- Lesson 3: Working with Connection Pools
- Lesson 4: Handling Connection Errors
- Lesson 5: Enumerating the Available SQL Servers on a Network
- Lesson 6: Securing Sensitive Connection String Data
- Chapter Review
- Suggested Practices
- Take a Practice Test
Lesson 4: Handling Connection Errors
This lesson explains how to handle errors that are thrown while you are working with SQL Server. ADO.NET provides two classes specifically for processing errors: the SqlException class and the SqlError class. Let’s see how to work with these classes and how to catch and handle errors that might be returned from the data source.
When SQL Server returns a warning or an error, the .NET Framework Data Provider for SQL Server creates and throws a SqlException that you can catch in your application to deal with the problem. When SqlException is thrown, inspect the SqlException.Errors property to access the collection of errors that is returned from the SQL server. The SqlException.Errors property is a SqlErrorCollection class (a collection of SqlError classes) that always contains at least one SqlError object.
Lab: Handling Database Connection Errors
In this lab you will practice catching a SqlException in your application.
EXERCISE 1: Handling Database Connection Errors
In this lab you will practice working with database connection errors (specifically, the SqlException and SqlError objects) in your application. To do this, let’s create a Windows application.
Create a new Windows application and name it HandlingConnectionErrors.
Add three buttons to the form and set the following properties:
Button1:
Name = GoodConnectButton
Text = Connect (valid connection string)
Button2:
Name = ConnectToInvalidUserButton
Text = Connect to invalid user
Button3:
Name = ConnectToInvalidDatabaseButton
Text = Connect to invalid database
Double-click each button to create the button click event handlers and switch to code view.
Add an Imports statement (using in C#) for the System.Data.SqlClient namespace.
The following code creates a new connection based on the connection string passed into it, attempts to open the connection, and then displays any errors it encounters. Add this code below the button click event handlers:
' VB Private Sub ConnectToDatabase(ByVal connectionString As String) Dim connection As New SqlConnection(connectionString) Try connection.Open() Catch ex As SqlException Dim errorMessage As String = "" ' Iterate through all errors returned ' You can check the error numbers to handle specific errors For Each ConnectionError As SqlError In ex.Errors errorMessage += ConnectionError.Message & " (error: " & _ ConnectionError.Number.ToString & ")" & Environment.NewLine If ConnectionError.Number = 18452 Then MessageBox.Show( _ "Invalid Login Detected, please provide valid credentials!") End If Next MessageBox.Show(errorMessage) Finally connection.Close() End Try End Sub // C# private void ConnectToDatabase(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); try { connection.Open(); } catch (SqlException ex) { string errorMessage = ""; // Iterate through all errors returned // You can check the error numbers to handle specific errors foreach (SqlError ConnectionError in ex.Errors) { errorMessage += ConnectionError.Message + " (error: " + ConnectionError.Number.ToString() + ")" + Environment.NewLine; if (ConnectionError.Number == 18452) { MessageBox.Show( "Invalid Login Detected, please provide valid credentials!"); } } MessageBox.Show(errorMessage); } finally { connection.Close(); } }
Add the following code so the three button click event handlers look like the following:
' VB Private Sub GoodConnectButton_Click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles GoodConnectButton.Click ' This is a valid connection string Dim GoodConnection As String = _ "Data Source=.\sqlexpress;Initial Catalog=Northwind;Integrated Security=True;" ConnectToDatabase(GoodConnection) End Sub Private Sub ConnectToInvalidUserButton_Click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles ConnectToInvalidUserButton.Click ' This connection string has invalid credentials Dim InvalidUserConnection As String = _ "Data Source=.\sqlexpress;Initial Catalog=Northwind;User ID = InvalidUser" ConnectToDatabase(InvalidUserConnection) End Sub Private Sub ConnectToInvalidDatabaseButton_Click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles ConnectToInvalidDatabaseButton.Click ' This connection string has an invalid/unavailable database Dim InvalidDatabaseConnection As String = _ "Data Source=.\sqlexpress;Initial Catalog=InvalidDatabase;" & _ "Integrated Security=True" ConnectToDatabase(InvalidDatabaseConnection) End Sub // C# private void GoodConnectButton_Click(object sender, EventArgs e) { // This is a valid connection string String GoodConnection = "Data Source=.\\sqlexpress;Initial Catalog=Northwind;Integrated Security=True"; ConnectToDatabase(GoodConnection); } private void ConnectToInvalidUserButton_Click(object sender, EventArgs e) { // This connection string has invalid credentials String InvalidUserConnection = "Data Source=.\\sqlexpress;Initial Catalog=Northwind;User ID = InvalidUser"; ConnectToDatabase(InvalidUserConnection); } private void ConnectToInvalidDatabaseButton_Click(object sender, EventArgs e) { // This connection string has an invalid/unavailable database String InvalidDatabaseConnection = "Data Source=.\\sqlexpress;Initial Catalog=InvalidDatabase;" + "Integrated Security=True"; ConnectToDatabase(InvalidDatabaseConnection); }
Run the application.
Click the Connect button. No errors should be raised.
Click the Connect To Invalid User button. The code to catch the specific login error (error 18452) is executed.
Click the Connect To Invalid Database button. You can see that an error was raised and is displayed in the message box.
Lesson Summary
A SqlException object is created when an error is detected on the SQL server.
Every instance of a SqlException exception contains at least one SqlError warning that contains the actual error information from the server.
Lesson Review
The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form.
What types of errors will cause a SqlConnection object to close? (Choose all that apply.)
Errors wth a severity level of 1 through 9
Errors wth a severity level of 10 through 19
Errors wth a severity level of 20 through 29
Errors wth a severity level of 30 or greater
What property contains the actual error message returned by SQL Server? (Choose all that apply.)
SqlException.Source
SqlException.Message
SqlError.Class
SqlError.Message