简体   繁体   中英

Mysql connection doesn't work with “using”

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM