我有一个SQLite数据库,该数据库返回1个数字到
Select value from Income where symbol = "AE" and statementitem = "Revenues" and periodtype = "Annual" and yearmonth = "Dec 2019";
--1811.2
我使用了一些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.
请问采用该值的最佳方法是什么?
请参阅官方文档:
它表明GetString
的唯一参数是“从零开始的列序号”。在您的情况下,您尝试访问第二项(按索引1),但是您的查询仅返回单个字段。在[>中使用索引0
answer = dataReader.GetString(0);