C#SQLite和SQL命令指定的强制转换无效
|
我正在玩SQlite和sql命令。我正在尝试制作一个测验程序,并且有一个循环,该循环从数据库中读取问题和答案,并将其添加到列表中。我还有一个布尔值,用于定义从数据库中选择的答案是对还是错。
我的问题是,在我的循环第一次执行代码并将true和false添加到bool数组时,所有这些工作正常,但是在我的循环执行第二次时,它抛出异常:SPECIFIED CAST NOT VALID。失败的方法如下所示:我在代码失败的地方添加了注释:
public void GetQuestion(int categoryRef)
{
Console.Clear();
int arrayIndex = 0;
int qListIndex = 0;
int idListIndex = 0;
List<string> qList = new List<string>();
List<int> idList = new List<int>();
int ansNr = 1;
bool[] isTrue = new bool[3];
SQLiteDataReader sqReader;
SQLiteCommand sqCommand = new SQLiteCommand(sqConnection);
try
{
sqCommand.CommandText = \"SELECT Question, ID FROM Questions WHERE CategoryRef=\" + categoryRef.ToString();
sqCommand.Connection.Open();
sqReader = sqCommand.ExecuteReader();
foreach (var item in sqReader)
{
qList.Add(sqReader.GetString(0));
idList.Add(sqReader.GetInt32(1));
}
sqReader.Close();
}
finally
{
sqConnection.Close();
}
for (int i = 0; i < qList.Count; i++)
{
try
{
sqCommand.CommandText = \"SELECT Answer FROM Answers WHERE QuestionRef=\" + idList[idListIndex].ToString();
sqConnection.Open();
sqReader = sqCommand.ExecuteReader();
Console.WriteLine(qList[qListIndex]);
foreach (var answer in sqReader)
{
Console.WriteLine(ansNr + \":\" + sqReader.GetString(0));
ansNr++;
}
sqReader.Close();
}
finally
{
sqConnection.Close();
}
try
{
//THIS CODE FAILS 2\'nd TIME IT LOOPS THROUGH
sqCommand.CommandText = \"SELECT IsTrue FROM Answers WHERE QuestionRef=\" + idList[idListIndex].ToString();
sqConnection.Open();
sqReader = sqCommand.ExecuteReader();
foreach (var item in sqReader)
{
isTrue[arrayIndex] = sqReader.GetBoolean(0); //<-- Specified cast is not valid.
arrayIndex++;
}
sqReader.Close();
}
finally
{
sqConnection.Close();
}
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
switch (number)
{
case 1:
if (isTrue[0] == true)
{
Console.WriteLine(\"Correct\");
}
if (isTrue[0] == false)
{
Console.WriteLine(\"False\");
}
break;
case 2:
if (isTrue[1] == true)
{
Console.WriteLine(\"Correct\");
}
if (isTrue[1] == false)
{
Console.WriteLine(\"False\");
}
break;
case 3:
if (isTrue[2] == true)
{
Console.WriteLine(\"Correct\");
}
if (isTrue[2] == false)
{
Console.WriteLine(\"False\");
}
break;
}
Console.ReadLine();
idListIndex++;
qListIndex++;
arrayIndex = 0;
ansNr = 1;
}
}
没有找到相关结果
已邀请:
3 个回复
秃拳割
艾食魄轻县
瓜唱鬼