Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top