各位,我用写代码的方式连上了一个数据库,然后用SqlDataReader 也可以读出数据库中的数据,只是每次在程序结束的时候都有一个异常,异常就是 “阅读器关闭时Read的尝试无效”,是什么原因啊。我觉得我在关闭数据库连接之前已经将DataReader这个阅读器关闭了啊~~~下面是我的一小段代码,看看是哪里出了问题啊 ,谢谢!
SqlDataReader dataReader = dataCommand.ExecuteReader(); //声明一个阅读器
while (dataReader.Read())
{
int teacherId = dataReader.GetInt32(0);
string teacherName = dataReader.GetString(1);
string teacherSex = dataReader.GetString(2);
int teaherAge = dataReader.GetInt32(3);
string teacherProf = dataReader.GetString(4);
int teacherSal = dataReader.GetInt32(5);
int teacherComm = dataReader.GetInt32(6);
string teacherDept = dataReader.GetString(7);
Console.WriteLine(
"Tno {0}\n Named {1}\n Sex {2}\n" +
"Age {3}\n Prof{4}\n Sal{5}\n Comm{6}\n Dept{7}\n\n",
teacherId, teacherName,teacherSex, teaherAge, teacherProf,
teacherSal, teacherComm, teacherDept);
dataReader.Close(); //关闭阅读器 }
}
catch(Exception e)
{
Console.WriteLine("Error accessing the database:" + e.Message );
}
finally
{
dataConnection.Close(); //每次都确保关闭了数据库连接
}