Flutter sqflite 插入列表<String>

Flutter sqflite insert List<String>

我试图在 flutter 中将列表插入 sql 数据库,但我不知道该怎么做,有人可以帮助我吗?

我在初始化 mi 数据库时有这个:

Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "tuCuestionarioDB.db");
    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {
      await db.execute("CREATE TABLE Question ("
          "id INTEGER PRIMARY KEY,"
          "subject INTEGER,"
          "topic INTEGER,"
          "question TEXT,"
          "answer INTEGER,"
          "answers TEXT ARRAY," //THIS IS MY LIST<STRING>
          "rightAnswer INTEGER,"
          "correctly BIT,"
          "answered BIT"
          ")");
    });

我用这个来插入数据:

 newQuestion(Question newQuestion) async {
     final db = await database;
    //get the biggest id in the table
    var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Question");
    int id = table.first["id"];
    //insert to the table using the new id
    var raw = await db.rawInsert(
        "INSERT Into Question (id,subject,topic,question,answer,answers,rightAnswer,correctly,answered)"
        " VALUES (?,?,?,?,?,?,?,?,?)",
        [id != null ? id : 0, newQuestion.subject, newQuestion.topic,newQuestion.question,newQuestion.answer,newQuestion.answers,newQuestion.rightAnswer,newQuestion.correctly ? 1 : 0,newQuestion.answered ? 1 : 0]);
    return raw;
  }

但是当您尝试插入这样的值时:

{subject: 1, topic: 1, question: What is the best community?, answer: 3, rightAnswer: 0, answers: [Stack Overflow, Facebook, Yahoo Answers], correctly: false, answered: false}

我遇到了这样的错误:

Exception has occurred.

SqfliteDatabaseException (DatabaseException(java.lang.String cannot be cast to java.lang.Integer) sql 'INSERT Into Question (id,subject,topic,question,answer,answers,rightAnswer,correctly,answered) VALUES (?,?,?,?,?,?,?,?,?)' args [0, 1, 1, What is the best community?, 3, [Stack Overflow, Facebook, Answers Yahoo], 0, 0, 0]})

当我删除 anwsers 字段时,我没有错误

我很确定您不能以这种方式存储字符串列表。根据 docs,它只支持一个 blob of ints。我认为有两种方法可以做到这一点。

一种方法是将答案串成一个字符串。您可以使用 join method and separate it by a character that no answer will contain (maybe a pipe like |). Then, when you read from the database, you can split 使用您选择的字符将字符串返回到数组中。

另一种方法是创建一个 table 将单个问题与多个答案相关联。这基本上是 sudo 代码,但如果你有一个匹配它的 table 它应该可以工作。

Answer

int id autoincremented, int questionId, String answerText, int isCorrectAnswer (0 or 1)

此外,有点不相关,但 sqflite 支持 AUTOINCREMENT 关键字,我建议您将其用于主键 ID。