C# Database Connection

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.

Ad Area

More

The try-catch block provides user feedback if an error occurs during database operations.

Ad Area

More
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);
            }
        }
    }
}

Ad Area

More
Author image
  • 16-09-2024
    Tags:

Comments

Leave a Comment

You may also like

C# - What Are Constructors and How to Use Them?

C# dilinde, yapıcı metodlar (constructors) bir sınıfın nesneleri ilk kez oluşturulduğunda çalışan özel metodlardır. Yapıcı metodlar sınıfın yapısını v...

Rise of Kingdoms Midterm Questions and Answers

Which country gifted the Statue of Liberty to the American people? France What was the reason sailors frequently suffered from scurvy in the past? L...