C # SQLite и команды SQL. Указанное приведение неверно. - PullRequest
0 голосов
/ 23 мая 2011

Я играю с командами SQlite и sql.Я пытаюсь создать программу викторины, и у меня есть цикл, который читает вопросы и ответы из моей базы данных и добавляет их в список.У меня также есть bool, который определяет, является ли ответ, выбранный из базы данных, правильным или неправильным.

Моя проблема заключается в том, что все это работает нормально, когда мой цикл выполняет код и добавляет значения true и false в мой массив.из bools, но во второй раз, когда мой цикл выполняет, он выдает исключение: 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 ]

3 голосов
/ 23 мая 2011

Скорее всего, вы читаете DbNull из базы данных, которую нельзя преобразовать в bool.

0 голосов
/ 31 января 2017

В моем случае EF выдавал ту же ошибку («Указанное приведение недопустимо»), поскольку он не мог разрешить «1234», который выдал SQLite.

SQLite type-affinityРешением было изменить тип поля «Имя» с STRING на TEXT .

0 голосов
/ 01 октября 2011

SQLite не гарантирует, что содержимое любого столбца будет соответствовать приведению.
GetBoolean не работает. У вас есть 3 варианта.

  1. Try Catch
  2. Тест на нуль
  3. Замените ваш выбор запросом, который гарантированно вернет true / false

    SQLite версия 3.7.8 2011-09-19 14: 49: 19
    sqlite> CREATE TABLE Q (A);
    sqlite> INSERT INTO Q VALUES (0);
    sqlite> INSERT INTO Q VALUES (1);
    sqlite> INSERT INTO Q VALUES ('T');
    sqlite> INSERT INTO Q VALUES ('F');
    sqlite> INSERT INTO Q VALUES ('Y');
    sqlite> INSERT INTO Q VALUES (NULL);
    sqlite> SELECT not ifnull (A == 0 ИЛИ A == 'F' ИЛИ ​​A == 'N', 1) ОТ Q;
    0
    1
    1
    0
    1
    0

...