如果SqlConnection C#检查连接打开,关闭

时间:2015-09-02 03:27:40

标签: c

我的代码不想返回紧密连接。 如果我没有太多的知识,我就无法使用它们。

 private void button1_Click(object sender, EventArgs e)
    {
        string connectionString = GetCString();

        using (SqlConnection connection = new SqlConnection(connectionString))


            if (connection.State == ConnectionState.Open)
            {
                connection.Open();
                Logger.getS().info_warning("Conexão Sucedida");
                Logger.getS().info_warning("DataSource : " + connection.DataSource);
                Logger.getS().info_warning("Banco De Dados : " + connection.Database);
                Logger.getS().info_warning("Versão do SQL : " + connection.ServerVersion);
                Logger.getS().info_warning("Status : " + connection.State);

                {

                }

            }
              else
              {

                  Logger.getS().info_erro("SqlConnection Não foi possivel connectar.");
                  Logger.getS().info_erro(" Status da Conexão : " + connection.State);


              }

        }

1 个答案:

答案 0 :(得分:0)

创建新连接时,最初始终关闭。然后,你需要打开它。但是,在打开连接之前检查连接是否已打开。

此后,在您的情况下,此条件永远不会是true

if (connection.State == ConnectionState.Open)

此外,您不需要检查其状态的连接。如果连接失败,它将抛出异常。您只需打开一个连接,并确保它可以正常工作或抛出异常。

应该是这样的:

try 
{
    string connectionString = GetCString();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Logger.getS().info_warning("Conexão Sucedida");
        Logger.getS().info_warning("DataSource : " + connection.DataSource);
        Logger.getS().info_warning("Banco De Dados : " + connection.Database);
        Logger.getS().info_warning("Versão do SQL : " + connection.ServerVersion);
        Logger.getS().info_warning("Status : " + connection.State);
    }
}
catch (Exception ex)
{ 
    Logger.getS().info_error("SqlConnection Não foi possivel connectar.");
    Logger.getS().info_error("SqlConnection exception message: " + ex.Message + "\r\n" + ex.StackTrace);
}

P.S。您可以将info_errorinfo_warning等实施为(string message, params string[] args)并使用String.Format。它可能会更方便:

Logger.getS().info_warning("Versão do SQL: {0}", connection.ServerVersion);