C# SQLite 和 SQL 命令指定的强制转换无效

发布于 2024-11-09 17:47:47 字数 3885 浏览 0 评论 0原文

我正在使用 SQlite 和 sql 命令。我正在尝试制作一个测验程序,我有一个循环,它从我的数据库中读取问题和答案并将它们添加到列表中。我还有一个布尔值,用于定义从数据库中选取的答案是正确还是错误。

我的问题是,当我的循环第一次执行代码并将 true 和 false 添加到我的布尔数组时,所有这些工作正常,但第二次我的循环执行时它会抛出异常: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;
        }
    }

I'm playing around with SQlite and sql commands. I'm trying to make a quizz program and I have a loop, that reads the questions and answers from my database and adds them to a list. I also have a bool that defines if the answer picked from the database is right or wrong.

My problem is that all this works fine the first time my loop executes the code and adds the true and false to my array of bools, but the 2'nd time my loop executes it throws the exception: SPECIFIED CAST NOT VALID. The method that fails looks like this: I made a comment where the code fails:

    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;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

握住我的手 2024-11-16 17:47:47

最有可能的是,您从数据库中读取了 DbNull,它无法转换为 bool。

Mostly likely, that you read DbNull from database, which cannot be cast to bool.

诗笺 2024-11-16 17:47:47

我收到同样的错误,因为 SQLite 返回 NULL。

检查是否为 null: if (!sqlite_datareader.IsDBNull(4))
{// 然后执行需要的操作}

I was getting the same error because SQLite was returning a NULL.

Check for null: if (!sqlite_datareader.IsDBNull(4))
{// then do what is required}

又怨 2024-11-16 17:47:47

SQLite 不保证任何列的内容都与强制转换匹配。
GetBoolean 失败。你有3个选择。

  1. 尝试
  2. 对 Null 进行 Catch Test
  3. 用保证返回 true/false 的查询替换您的选择

    SQLite版本3.7.8 2011-09-19 14:49:19
    sqlite>创建表 Q (A);
    sqlite>插入 Q 值 (0);
    sqlite>插入 Q 值 (1);
    sqlite>插入 Q 值 ('T');
    sqlite>插入 Q 值 ('F');
    sqlite>插入 Q 值 ('Y');
    sqlite>插入 Q 值(空);
    sqlite> SELECT not ifnull(A==0 OR A=='F' OR A=='N',1) FROM Q;
    0
    1
    1
    0
    1
    0

SQLite does not guarantee that the contents of any column will match the cast.
The GetBoolean is failing. You have 3 choices.

  1. Try Catch
  2. Test for Null
  3. Replace your select with a query guaranteed to return true/false

    SQLite version 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 OR A=='F' OR A=='N',1) FROM Q;
    0
    1
    1
    0
    1
    0

你如我软肋 2024-11-16 17:47:47

就我而言,EF 抛出了相同的错误(“指定的转换无效”),因为它无法解析 SQLite 抛出的“1234”。

SQLite 类型-亲和力
解决方案是将名称字段的类型从 STRING 更改为 TEXT

In my case, EF was throwing the same error ("Specified cast not valid") because it couldnt resolve "1234" that SQLite was throwing at it.

SQLite type-affinity
The solution was to change the type of Name field from STRING to TEXT.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文