尝试从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;
}
答案 0 :(得分:1)
在尝试使用它生成的SqlReader之前,您已经处置了SqlCommand。在阅读完毕之前,他们都需要保持开放状态。