在调用Read()之前试图访问字段无效,但我先调用Read()
本文关键字:Read 调用 无效 字段 访问 | 更新日期: 2023-09-27 18:04:50
我试图从MySQL数据库处理一些数据(主要是双值)。我得到这个错误信息:
Invalid attempt to access a field before calling Read()
观察窗口:
readerCompare1["Fe1"] 'readerCompare1["Fe1"]' threw an exception of type 'MySql.Data.MySqlClient.MySqlException' object {MySql.Data.MySqlClient.MySqlException}
我以前用过这段代码,它工作得很好。
代码: for (int k = 1; k <= pocet; k++)
{
string queryCompare = " SELECT F1 AS Fe1, F2 AS Fe2, F3 AS Fe3, F4 AS Fe4, F5 AS Fe5, F6 AS Fe6, F7 AS Fe7, F8 AS Fe8, cluster FROM features WHERE ID=" + k;
MySqlCommand cmdCompare = new MySqlCommand(queryCompare, conect);
readerCompare1 = cmdCompare.ExecuteReader();
readerCompare1.Read();
// MessageBox.Show("OK");
double f1 = Convert.ToDouble(readerCompare1["Fe1"].ToConvertibleDouble()); //Exception THROWN HERE
double f2 = Convert.ToDouble(readerCompare1["Fe2"].ToConvertibleDouble());
double f3 = Convert.ToDouble(readerCompare1["Fe3"].ToConvertibleDouble());
double f4 = Convert.ToDouble(readerCompare1["Fe4"].ToConvertibleDouble());
double f5 = Convert.ToDouble(readerCompare1["Fe5"].ToConvertibleDouble());
double f6 = Convert.ToDouble(readerCompare1["Fe6"].ToConvertibleDouble());
double f7 = Convert.ToDouble(readerCompare1["Fe7"].ToConvertibleDouble());
double f8 = Convert.ToDouble(readerCompare1["Fe8"].ToConvertibleDouble());
// string f88 = readerCompare["Fe8"].ToString();
//double f8 = Convert.ToDouble(f88, CultureInfo.InvariantCulture);
int cluster = Convert.ToInt32(readerCompare1["cluster"].ToString());
readerCompare1.Close();
在:double f1 = Convert这一行抛出异常。ToDouble (readerCompare1 [" Fe1 "]…
但是正如你所看到的,我首先调用了Read():
readerCompare1.Read();
谁能解释一下,为什么会发生这种情况?谢谢你
Read
方法返回一个布尔值,告诉您是否有任何信息可用。如果返回false,则不能尝试从读取器读取。
你应该用if语句(或者while语句,取决于你期望得到多少个结果)来包装你的代码:
if(readerCompare1.Read()) {
double f1 = Convert.ToDouble(readerCompare1["Fe1"].ToConvertibleDouble());
double f2 = Convert.ToDouble(readerCompare1["Fe2"].ToConvertibleDouble());
double f3 = Convert.ToDouble(readerCompare1["Fe3"].ToConvertibleDouble());
double f4 = Convert.ToDouble(readerCompare1["Fe4"].ToConvertibleDouble());
double f5 = Convert.ToDouble(readerCompare1["Fe5"].ToConvertibleDouble());
double f6 = Convert.ToDouble(readerCompare1["Fe6"].ToConvertibleDouble());
double f7 = Convert.ToDouble(readerCompare1["Fe7"].ToConvertibleDouble());
double f8 = Convert.ToDouble(readerCompare1["Fe8"].ToConvertibleDouble());
}
MySqlDataReader示例