The following example uses the SqlConnection class to connect to a database.
The connection string (connectionString), Data Source, Initial Catalog, User ID and Password properties. The SqlConnection object is defined within the using statement, so it is automatically disposed of once the database connection operation is complete.
The try-catch block provides user feedback if an error occurs during database operations.
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Define the information required for the database connection.
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword";
// Create the database connection.
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
// Open the database connection.
connection.Open();
// Perform your database operations.
// Close the database connection.
connection.Close();
}
catch (Exception e)
{
// Provide feedback if an error occurs.
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
}
Comments
Leave a Comment