-3
connectionString = @"server=localhost;database=" + lbDatabase.SelectedItem.ToString() + ";userid=root;password=;";

        string query = "SELECT order_id FROM orders WHERE id = 1";

        MySqlConnection connect = new MySqlConnection(connectionString);

        MySqlCommand cmd = new MySqlCommand(query, connect);

        reader = cmd.ExecuteReader();

Hello,

I have this problem when I run the following code. I get this not so very specific error:

An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll

Additional information: Connection must be valid and open.

If anyone could help me out I would really appreciate it,

Thank you.

Tom Tom
  • 3,680
  • 5
  • 35
  • 40
Quartermain
  • 163
  • 3
  • 17
  • 4
    Well the exception seems pretty clear. You don't have a valid, open connection. Look at your code - where do you think you're opening the connection? Try `connect.Open()`... – Jon Skeet Feb 23 '15 at 10:56
  • The connection is already opened by another methode. When I add connect.Open() it says the connection is already open. – Quartermain Feb 23 '15 at 11:00
  • Then there's code you haven't shown us, which makes it hard to help you... – Jon Skeet Feb 23 '15 at 11:00
  • http://pastebin.com/gHaHqxcr – Quartermain Feb 23 '15 at 11:02
  • No, please edit this question - it should be standalone. – Jon Skeet Feb 23 '15 at 11:14
  • I up voted just because, after programming for 12 hours straight, I also left out the Open statement ... then spent 10 minutes wondering what was wrong. Sometimes the obvious mistakes are the ones we don't see. Thank goodness for SO! :D – Yogi Sep 17 '16 at 06:41

2 Answers2

0

The syntax for MySql Connectionstring is as follows:

Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Note that you are using 'userid' and 'password' instead of 'uid' and 'pwd'.

0

Assuming that your Connection String is Right .. Try This

connectionString = @"server=localhost;database=" + lbDatabase.SelectedItem.ToString() + ";userid=root;password=;";

    string query = "SELECT order_id FROM orders WHERE id = 1";

    MySqlConnection connect = new MySqlConnection(connectionString);


    MySqlCommand cmd = new MySqlCommand(query, connect);

    connect.Open();

    reader = cmd.ExecuteReader();

 /*Do Whatever You Want To Do Here */

connect.Close();

You Can Refer this Link for Reference. Exception: System.InvalidOperationException Trying to validate a login information

Hope This Helps :)

Community
  • 1
  • 1
Gaurav Modi
  • 82
  • 1
  • 10