Reader关闭时读取的次数无效 - MySqlDataReader C#

时间:2018-04-16 19:07:22

标签: c# sql .net mysqldatareader

尝试从DataReader读取时,在Invalid attempt to read when Reader is closed方法中获取duplicateNameCheck异常。我不知道为什么。非常感谢任何帮助!

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;                                       
}

1 个答案:

答案 0 :(得分:1)

在尝试使用它生成的SqlReader之前,您已经处置了SqlCommand。在阅读完毕之前,他们都需要保持开放状态。