如何在sqflite中的数据库中创建多个表?

时间:2019-01-22 20:40:37

标签: android sqlite dart flutter sqflite

Im建筑物和使用SQLite数据库的扑朔迷离的应用程序。我使用这段代码创建了第一个表:

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

表已创建,我可以毫无问题地访问它。

不幸的是,我不能包含刚刚创建的多个表。我尝试在同一方法中添加另一个SQL CREATE TABLE子句,并在下一行中使用不同的SQL子句重复方法db.execute

我正在模仿本教程中的代码:https://www.youtube.com/watch?v=xke5_yGL0uk

如何在同一数据库中添加另一个表?

6 个答案:

答案 0 :(得分:2)

您可以合并多个db.execute调用作为示例

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
       )''');

答案 1 :(得分:1)

是的,您可以做到

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

但是为了加快该过程,假设我们有10个表,您可以通过这种方式使用批处理

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
}

答案 2 :(得分:1)

在openDatabase中(路径,onCreate,版本) 使用另一个可选参数“ onUpgrade”,并定义删除并再次创建表脚本。并且还将参数版本升级(增加)一个。

-----代码段------

openDatabase(path, onCreate:_createDb, onUpgrade: onUpgrade,version:_DB_VERSION);
...
...

    _onUpgrade( Database db, int oldVersion, int newVersion ) async {

    Batch batch = db.batch();

    // drop first

    batch.execute("DROP TABLE IF EXISTS $_TABLE_3 ;");

    batch.execute("DROP TABLE IF EXISTS $_TABLE_2 ;");
    batch.execute("DROP TABLE IF EXISTS $_TABLE_1 ;");
    // then create again
    batch.execute("CREATE TABLE $TABLE_1 ...... ");
    batch.execute("CREATE TABLE $TABLE_2 ...... ");
    batch.execute("CREATE TABLE $TABLE_3 ...... ");
    List<dynamic> result = await batch.commit();

}

注意:每次创建或更改某些表的结构时,都必须使用openDatabase()方法增加数据库版本。这样升级将被调用,否则将不被调用。

答案 3 :(得分:0)

不用说openDatabase呼叫以及数据库是否存在就很难说。我的猜测之一是您仍在使用相同的数据库版本。一旦onCreate被调用,它将不再被调用。您应该尝试更改数据库版本,然后在onUpgrade

上添加新表

答案 4 :(得分:0)

更改DB文件的名称。这将“重置”您的数据库,并且创建将起作用。

例如:

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

答案 5 :(得分:0)

您可以使用包含数据库脚本的.sql文件。

首先,将脚本文件添加到资产中。

然后,导入以下软件包:

import 'package:path/path.dart';

import 'package:sqflite/sqflite.dart';

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

最后,使用以下代码

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