Technology

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
Tags:

Comments

Leave a Comment

You may also like

C# Database Connection

Nedese

Nedese Panel

To start a free trial, all you need to do is go to the user management panel. Simplify your processes and increase your productivity with our tools tailored to your needs!

Start Your Free Trial
NedeseAI