0

尝试从 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;                                       
}
4

1 回答 1

1

在尝试使用它生成的 SqlReader 之前,您正在处理 SqlCommand。在您完成阅读器之前,它们都需要保持打开状态。

于 2018-04-16T19:13:36.493 回答