SqlDataConnection Class

System.Data

Represents a connection to a SQL Server database. This class is part of the System.Data.SqlClient namespace.

The SqlDataConnection class provides a way to establish a connection to a Microsoft SQL Server database, execute commands, and retrieve results.

Inheritance

System.Object > System.MarshalByRefObject > System.Data.Common.DbConnection > System.Data.SqlClient.SqlConnection

Syntax

public sealed class SqlConnection : DbConnection

Remarks

The SqlConnection object is intended for use within the same thread. Even if you are using threading to call SqlConnection methods, you should use an instance of SqlConnection within a single thread.

When you inherit from SqlConnection, you must implement the inherited abstract members. The SqlConnection class is sealed and cannot be inherited directly. For scenarios that require custom connection behavior, consider implementing the IDbConnection interface or extending the DbConnection class using the DbProviderFactory pattern.

Members

Constructor
SqlConnection(string connectionString)
(string connectionString);
Constructor
ConnectionString
get; set;
Property
State
get;
Property
Open()
();
Method
Close()
();
Method
Method

Example

The following example demonstrates how to create a SqlConnection, open it, execute a query, and then close the connection.

using System;
using System.Data;
using System.Data.SqlClient;

public class Example
{
    public static void Main()
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                Console.WriteLine("Connection opened successfully.");

                SqlCommand command = connection.CreateCommand();
                command.CommandText = "SELECT COUNT(*) FROM MyTable;";

                object result = command.ExecuteScalar();
                Console.WriteLine($"Number of rows: {result}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    Console.WriteLine("Connection closed.");
                }
            }
        }
    }
}

See Also