12

I have this code down which I tried to make it Test SQL string connectivity, but I dont know how to handle the part with connection.Open = true would you please help me to solve this out? Thank you so much for your time.

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection("Data Source='" + textBox1.Text + "';Initial Catalog='" + textBox2.Text + "';User ID='" + textBox3.Text + "';Password='" + textBox4.Text + "'"))
            {
                try
                {
                    connection.Open();
                    if (connection.Open == true) // if connection.Open was successful
                    {
                        MessageBox.Show("You have been successfully connected to the database!");
                    }
                    else
                    {
                        MessageBox.Show("Connection failed.");
                    }
                }
                catch (SqlException) { }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Chyba v přihlášení: " + ex);
        }
        finally
        {

        }
    }

It says: "Cannot asign 'open' because it is a 'methoud group' " I know that this code might be totaly bad, but I need to handle this somehow and have no idea what is the right way. Thank you.

This is what is not actually working for not-opened connection:

using (SqlConnection connection = new SqlConnection("Data Source='" + textBox1.Text + "';Initial Catalog='" + textBox2.Text + "';User ID='" + textBox3.Text + "';Password='" + textBox4.Text + "'"))
        {

             connection.Open();

            if (connection.State == ConnectionState.Open)
            {

                MessageBox.Show("Spojení s databázi problěhlo úspěšně.");
            }
            connection.Close();
            if (connection.State == ConnectionState.Closed)
            {
                MessageBox.Show("Spojení selhalo");
            }
        }
4

2 回答 2

20

你使用connection.Open = true它就好像它是一个属性。

这是一种方法:connection.Open()

使用ConnectionState枚举来确定连接是否打开,例如:

connection.State == ConnectionState.Open
于 2013-07-25T08:58:50.533 回答
3

您需要检查它是否被此代码打开:

if(connection.State == ConnectionState.Open)
{
  ...
}
于 2013-07-25T09:01:16.137 回答