John Ryann
John Ryann

Reputation: 2393

C# MySQL connection multiple select statements

I can connect to MySQL database from my WinForms app fine. The question is once I am logged in how can I perform multiple select statements without having to login again?

MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();

MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;

command.CommandText = "select id from user ";

Then I want to perform a select statement for another table without having to create connection again. How do I dothis? I can't seem to just do connection.CreateCommand.

Upvotes: 2

Views: 7939

Answers (2)

Joel B Fant
Joel B Fant

Reputation: 24756

I see you're using a DataReader. You can only have 1 DataReader open at a time per connection. using blocks come in handy for those:

using( var reader = myCommand.ExecuteReader() ) {
    while (reader.Read()) {
        // get values, do stuff
    }
}// reader gets closed

You only hint at it in the code in your question (currently), but it's possible that is part of your problem. You haven't shown how you're using the DataReader, so I'm not certain. Just a possibility.

Upvotes: 0

DRapp
DRapp

Reputation: 48139

As long as the queries are within the same block, you can use the same connection.. However, once closed, you need to re-open it.

using( YourConnectionObject )
{
   ... open connection ...
   ... create your sql querying object... and command 
   SQLCommand.Connection = YourConnectionObject;

   Execute your Query

   SQLCommand.CommandText = "a new sql-select statement";

   Execute your NEW query while connection still open/active

   SQLCommand.CommandText = "a third sql-select statement";

   Execute your THIRD query while connection still open/active

   ... close your connection
}

However, in your application, you can have a single "connection" object like at the application level, or at a form level with the necessary login / connection settings stuff. Then, internally to each form, you can

Open
Run Query
Run Query
Run Query
Close

as needed.

Upvotes: 2

Related Questions