8

Hi I am connecting to MySQL in C# and I need to check is the SQL connection open or not. If open then do something or if not do something. I am trying by below code but I am getting error.

var sqlCon= new SqlConnection(Properties.Settings.Default.sString);
var mySQLCon= new MySqlConnection(Properties.Settings.Default.dString);
sqlCon.Open();
mySQLCon.Open();
if (sqlCon.State==ConnectionState.Open && mySQLCon.State==ConnectionState.Open)
  {
    MessageBox.Show(@"Connection working.");
  }
else
  {
    MessageBox.Show(@"Please check connection string");
  }

I am getting error on mySQLCon.State==ConnectionState.Open Error is InvalidOperationException How can we check the MySQL connection state.

4
  • 1
    If the Open call fails, I'd expect an exception to be thrown anyway... Commented Dec 26, 2013 at 12:58
  • Sorry for incomplete information. I have updated my question. Commented Dec 26, 2013 at 13:00
  • 1
    It seems very strange that you get the exception on the line that checks the connection state. Looking at the sources there is nothing there that could throw an exception. It is more likely that you have a problem in the Open command Commented Dec 26, 2013 at 13:04
  • 1
    As a side note, you should always close/dispose unmanaged resources. Commented Dec 26, 2013 at 13:04

1 Answer 1

11

I think error should be in connection string. Check your connection string first.

if connection string is correct and there is some another issue try something like below.

var sqlCon= new SqlConnection(Properties.Settings.Default.sString);
var mySQLCon= new MySqlConnection(Properties.Settings.Default.dString);
sqlCon.Open();
mySQLCon.Open();
var temp = mySQLConn.State.ToString();
if (sqlCon.State==ConnectionState.Open && temp=="Open")
 {
   MessageBox.Show(@"Connection working.");
 }
else
 {
  MessageBox.Show(@"Please check connection string");
 }

And one more thing as @Leri mentioned you should always close/dispose unmanaged resources. Hope it work for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes sir. I think there was problem in unmanaged resources. I have restarted the system and it worked. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.