测试数据库内容,放大1个值

问题描述 投票:0回答:1

我有一个SQLite数据库,该数据库返回1个数字到

Select value from Income where symbol = "AE" and statementitem = "Revenues" and periodtype = "Annual" and yearmonth = "Dec 2019"; --1811.2

enter image description here

我使用了一些C#代码进行测试,以确保不会遗漏任何内容:

    public string GetIncome(string dbFile, string symbol, string aq, string yearmonth)
    {
        var answer = String.Empty;

        try
        {
            using (var con = new SQLiteConnection($"URI=file:{dbFile}"))
            {
                con.Open();
                using var cmd = new SQLiteCommand(con)
                {
                    CommandText = $"Select value from Income where symbol = '{symbol}' and statementitem = 'Revenues' and periodtype = '{aq}'  and yearmonth = '{yearmonth}';"
                };

                using SQLiteDataReader dataReader = cmd.ExecuteReader();

                while (dataReader.Read())
                {
                    answer = dataReader.GetString(1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw ex;
        }


        return answer;
    }

此错误显示为System.IndexOutOfRangeException : Index was outside the bounds of the array.

请问采用该值的最佳方法是什么?

c# sqlite
1个回答
0
投票

请参阅官方文档:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitedatareader.getstring?view=msdata-sqlite-3.1.0#Microsoft_Data_Sqlite_SqliteDataReader_GetString_System_Int32_

它表明GetString的唯一参数是“从零开始的列序号”。在您的情况下,您尝试访问第二项(按索引1),但是您的查询仅返回单个字段。在[>中使用索引0

answer = dataReader.GetString(0);
© www.soinside.com 2019 - 2024. All rights reserved.