In ADO.NET, error handling is an essential part of database programming to manage exceptions that may occur during database operations. Let's see how you can handle errors using SqlConnection, SqlCommand, and SqlDataReader objects in an ASP.NET application:
Example:
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void ConnectToDatabase()
{
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
try
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
Console.WriteLine("Connection successful.");
connection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Exception: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
Example:
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void ExecuteSqlCommand()
{
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
string query = "SELECT * FROM NonExistingTable"; // Incorrect table name
try
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
connection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Exception: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
Example:
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void ReadData()
{
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
string query = "SELECT * FROM YourTable";
try
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Attempting to access data without checking if reader has rows
while (reader.Read())
{
int id = reader.GetInt32(0); // This may throw an exception if there are no rows
}
connection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Exception: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
By using try-catch blocks, you can handle exceptions gracefully and provide appropriate error messages or take corrective actions in your ASP.NET application.