Connecting to a Database using System.Data.SqlClient
The SqlConnection
class in System.Data.SqlClient
is used to establish a connection to a SQL Server database. This example demonstrates how to set up a connection string and connect to the database securely.
Key Topics
Basic Connection
Example
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUser;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("Database connected successfully.");
}
}
}
Explanation: This example uses the SqlConnection
class to open a connection to the database. The using
statement ensures that the connection is properly closed and disposed of after use.
Connection with Error Handling
Example
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUser;Password=myPassword;";
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("Database connected successfully.");
}
}
catch (SqlException ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Explanation: This example adds error handling using a try-catch
block to catch SQL-related exceptions and display an appropriate error message.
Key Takeaways
- Use the
SqlConnection
class to connect to a SQL Server database. - The
using
statement ensures proper resource cleanup after database operations. - Error handling is essential to manage exceptions like invalid connection strings or network issues.