How to create multiple tables in a database in sqflite?

狂风中的少年 提交于 2019-12-19 17:40:07

问题


Im building and app with flutter that uses SQLite database. I have created first table using this piece of code:

 void _createDb(Database db, int newVersion) async {
    await db.execute('''CREATE TABLE cards (id_card INTEGER PRIMARY KEY, 
         color TEXT, type TEXT, rarity TEXT, name TEXT UNIQUE, goldCost INTEGER,
         manaCost INTEGER, armor INTEGER, attack INTEGER, health INTEGER, description TEXT)''');
}

Table gets created and I can access it without problems.

Unfortunately I cannot include more than 1 table that i just created. I tried adding another SQL CREATE TABLE clause in the same method, and repeating method db.execute with a different SQL clause just in the next line.

I'm mimicing code from this tutorial: https://www.youtube.com/watch?v=xke5_yGL0uk

How to add another table within the same database?


回答1:


You can just combine multiple db.execute calls for exampple

await db.execute('''
      create table $reminderTable (
        $columnReminderId integer primary key autoincrement,
        $columnReminderCarId integer not null,
        $columnReminderName text not null,
        $columnReminderNotifyMileage integer not null,
        $columnReminderEndMileage integer not null
       )''');
await db.execute('''
       create table $carTable (
        $columnCarId integer primary key autoincrement,
        $columnCarTitle text not null
       )''');



回答2:


Change the name of the DB file. This will 'reset' your DB and creation will work.

e.g:

final dabasesPath = await getDatabasesPath(); 
final path = join(dabasesPath, "newName2.db");



回答3:


yes you can do it

 void _createDb(Database db, int newVersion) async {
 await db.execute('''
   create table $carTable (
    $columnCarId integer primary key autoincrement,
    $columnCarTitle text not null
   )''');
 await db.execute('''
   create table $userTable(
    $userId integer primary key autoincrement,
    $name text not null
   )''');
  }

but to speed up the process, let's assume we have 10 tables, you could use the batch this way

void _createDb(Database db, int newVersion) async {
Batch batch = db.batch();
batch.execute("Your query-> Create table if not exists");
batch.execute("Your query->Create table if not exists");
List<dynamic> res = await batch.commit();
//Insert your controls
}



回答4:


Hard to say without seeing your openDatabase call and whether the database exists before or not. One of my guess is that you are still using the same database version. Once onCreate has been called it will never be called again. You should try to bump your database version and add the new table in on onUpgrade




回答5:


You can use a .sql file that contains your DB script.

First,add the script file to assets.

Then, import the following packages:

import 'package:path/path.dart';

import 'package:sqflite/sqflite.dart';

import 'package:flutter/services.dart' show rootBundle;

finally, use the following code

void _createDb() async 
{
      final database = openDatabase( join( await getDatabasesPath(), 'mydb.db'),
      onCreate: (db, version) async  
      {
          // call database script that is saved in a file in assets
          String script =  await rootBundle.loadString("assets\\db\\script.sql");
          List<String> scripts = script.split(";");
          scripts.forEach((v) 
          {
              if(v.isNotEmpty ) 
              {
                   print(v.trim());
                   db.execute(v.trim());
              }
          });
       },
       version: 1,
       );
}


来源:https://stackoverflow.com/questions/54316131/how-to-create-multiple-tables-in-a-database-in-sqflite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!