0

I'm trying this

string query = "SELECT * FROM teams ORDER BY name";

using(MySqlConnection dbConn = new MySqlConnection(conn))
{
    MySqlCommand cmd = new MySqlCommand(query, dbConn);
    MySqlDataReader dataReader = cmd.ExecuteReader();

But it returns an error on MysqlCommand line, saying Connection must be valid and open. Anyone have an idea what am I doing wrong?

1
  • 4
    Error message is so clear IMO.. Commented Nov 13, 2013 at 20:24

1 Answer 1

10

You haven't open the connection in your code, You should call

dbConn.Open();

It has nothing to do with using statement.

string query = "SELECT * FROM teams ORDER BY name";
using(MySqlConnection dbConn = new MySqlConnection(conn))
{
    MySqlCommand cmd = new MySqlCommand(query, dbConn);
    dbConn.Open();//here **
    MySqlDataReader dataReader = cmd.ExecuteReader();

using statement only ensures that the your connection object will be disposed after the scope, it doesn't open the connection itself.

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

1 Comment

You should wrap the command object in a using too, Habib. +1 regardless.

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.