How can the connection status of a SQL Server database be determined in C#?

To check the status of a C# connection to a SQL Server database, you can use the State property of the SqlConnection object. This property returns an enumeration value that represents the connection status, common values include:

  1. Closed: The connection has been terminated.
  2. Connection has been opened.
  3. Connection is being attempted to open.
  4. Executing: Connecting and carrying out the command.
  5. Fetching: The connection is currently retrieving data.
  6. Disconnected: The connection has been severed.

Here is a simple sample code demonstrating how to obtain the connection status.

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=serverName; Initial Catalog=databaseName; User ID=userName; Password=password";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            Console.WriteLine("连接状态: " + connection.State);

            // 执行一些数据库操作

            Console.WriteLine("连接状态: " + connection.State);
        }
    }
}

In the example above, we first create a SqlConnection object and initialize it with a connection string. Next, we call the Open method to open the database connection. Before and after performing operations on the database, we can obtain the connection state through the State property of the connection object and print it out. Finally, we use the using statement to ensure that the connection is closed after use.

Note: In practical application, the connection status should be handled according to the specific situation and needs, for example, reopening the connection when it is Closed, or reconnecting to the database when it is Broken.

bannerAds