Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to test SQL connection string availibility

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");
            }
        }
like image 613
Marek Avatar asked Jul 25 '13 08:07

Marek


People also ask

Which is the most recommended way to save the connection string?

The best way to secure the database connection string is to encrypt the value within the configuration file. The application would then load the encrypted value from the config file, decrypt the value, and then use the decrypted value as the connection string to connect to the database.


1 Answers

You're using connection.Open = true as if it were a property.

It's a method: connection.Open()

Use the ConnectionState enum to determine if the connection is open or not, eg:

connection.State == ConnectionState.Open
like image 167
DGibbs Avatar answered Nov 15 '22 23:11

DGibbs