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

fil*_*ard 7 sqlite android dart flutter sqflite

我正在使用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)''');
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Ale*_*Pad 15

是的,你可以做到

 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
   )''');
  }
Run Code Online (Sandbox Code Playgroud)

但为了加快进程,假设我们有 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
}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

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

然后,导入以下包:

import 'package:path/path.dart';

import 'package:sqflite/sqflite.dart';

import 'package:flutter/services.dart' show rootBundle;
Run Code Online (Sandbox Code Playgroud)

最后,使用以下代码

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,
       );
}
Run Code Online (Sandbox Code Playgroud)


use*_*123 5

您可以将多个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
       )''');
Run Code Online (Sandbox Code Playgroud)


ale*_*xtk 2

openDatabase如果没有看到你的电话以及数据库之前是否存在,很难说。我的猜测之一是您仍在使用相同的数据库版本。一旦onCreate被调用,就永远不会再被调用。您应该尝试提高数据库版本并添加新表onUpgrade