我正在尝试处理来自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 examples