2

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.

4
  • Well, you can use the same connection object again for a different query Commented Jun 20, 2011 at 17:37
  • 1
    show your full code for help you. Commented Jun 20, 2011 at 17:38
  • Check think post once codeproject.com/Answers/201603/… Commented Jun 20, 2011 at 17:42
  • yes as @rahul told you can open connection globaly in your project and run the other query for other table. Commented Jun 20, 2011 at 17:44

2 Answers 2

2

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.

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

Comments

0

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.

Comments

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.