0

Getting an Invalid attempt to read when Reader is closed exception in my duplicateNameCheck method, when attempting to read from the DataReader. I'm not sure why. Any help is greatly appreciated!

public static MySqlConnection GetSqlConnection() {
    MySqlConnection connection = new MySqlConnection(connectionString);

    return connection;
}

public static MySqlDataReader ExecuteReader(string sqlQuery, MySqlConnection connection) {
    using (MySqlCommand command = new MySqlCommand(sqlQuery, connection)) {     
        try {
            connection.Open();                                      
            MySqlDataReader sqlReader = command.ExecuteReader();    

             return sqlReader;                                       
         } catch (Exception ex) {
             MessageBox.Show(ex.Message);                            
             return null;                                            
         }
    }
}

public static bool duplicateNameCheck(string inName) {
    String sqlQuery = "SELECT * FROM Account";    

    using (MySqlDataReader sqlReader = SQLHelper.ExecuteReader(sqlQuery, SQLHelper.GetSqlConnection())) {

        while (sqlReader.Read())
        {                     
            if (inName.Equals(sqlReader[1].ToString(), StringComparison.InvariantCultureIgnoreCase))
            {  
                return true;
            }
        }
    }
    return false;                                       
}
dsdel
  • 1,042
  • 1
  • 8
  • 11
kevin
  • 15
  • 1
  • 4
  • Don't catch an exception in `SQLHelper.ExecuteReader()` and return null. You're pretending, in that case, that the whole thing didn't totally fail. But it did. It utterly failed, and the caller is not getting back a SqlDataReader. That's what exceptions are for. Maybe the catch belongs in `duplicateNameCheck()`, maybe in its caller. But not where it is. Considering glenebob's valid and important point, the whole helper thing seems pointless. What is all the `MySql*` stuff about? – 15ee8f99-57ff-4f92-890c-b56153 Apr 16 '18 at 19:13
  • When `MySqlCommand` is disposed (before the using block exits), the reader is also disposed because the `MySqlCommand` created it. When the reader is disposed, it is also closed. I am not sure if the connection is still open or close; because the connection object is created outside, it should not be closed (would be interesting to test and find out). – CodingYoshi Apr 16 '18 at 19:34

1 Answers1

1

You're disposing the SqlCommand before attempting to use the SqlReader it produced. They'll both need to stay open until you're done with the reader.

glenebob
  • 1,943
  • 11
  • 11