InvalidOperationExcption未处理

时间:2013-05-11 17:29:06

标签: c# windows-services

当我输入此代码时:

        query = "SELECT DateString FROM table WHERE DateArrivage = 'DefaultValue' ";
        OdbcDataReader DbR = ObAccess.SQLSELECT(query);
        int fCount = DbR.FieldCount;
        if (fCount > 0)
        {

            DateWithoutDate = DbR.GetString(0); // i wan't only first value
            DbR.Close();
        }
        else
        {
            int row_count = DbR.RecordsAffected;
            Console.WriteLine("Query affected " + row_count + " row(s)");
        }

它给出了我在标题中写的错误, 有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您没有在数据阅读器上调用Read(),因此逻辑上它位于第一行之前。我怀疑你真的想要:

query = "SELECT DateString FROM table WHERE DateArrivage = 'DefaultValue' ";
using (OdbcDataReader reader = ObAccess.SQLSELECT(query))
{
    if (reader.Read())
    {
        DateWithoutDate = reader.GetString(0);
    }
    else
    {
        // Whatever you want to do if there are no rows
    }
}

同样令人担心的是,您有ObAccessSQLSELECT等名称...而且您似乎没有在此代码中打开和关闭连接,这通常是一个好主意。 (不要试图保持单个连接自己打开并重用它 - 让底层数据库连接池为你做这件事。)