【问题标题】:How to check if a database exists before creating a table?如何在创建表之前检查数据库是否存在?
【发布时间】:2019-12-05 23:14:39
【问题描述】:

在使用sqfliteFlutter中的数据库创建表之前如何检查数据库是否存在?

例如,如果我要创建数据库doggie_database.db,如何在创建表时过早检查它的存在?

final Future<Database> database = openDatabase(
  // Set the path to the database. 
  join(await getDatabasesPath(), 'doggie_database.db'),
  // When the database is first created, create a table to store dogs.
  onCreate: (db, version) {
    // Run the CREATE TABLE statement on the database.
    return db.execute(
      "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
    );
  },
  // Set the version. This executes the onCreate function and provides a
  // path to perform database upgrades and downgrades.
  version: 1,
);

【问题讨论】:

    标签: flutter sqflite


    【解决方案1】:

    您可以使用databaseExists(String path) 检查数据库是否存在。

    https://github.com/tekartik/sqflite/blob/master/sqflite/lib/sqflite.dart(第 174 行)

    /// Check if a database exists at a given path.
    ///
    Future<bool> databaseExists(String path) =>
        databaseFactory.databaseExists(path);
    

    但我认为您担心再次调用 CREATE TABLE 语句。如果您指定version,则不必担心这一点。在内部保留版本,如果已指定 onCreate,则不会调用它。

    来自同一个文件:

    /// If [version] is specified, [onCreate], [onUpgrade], and [onDowngrade] can
    /// be called. These functions are mutually exclusive — only one of them can be
    /// called depending on the context, although they can all be specified to
    /// cover multiple scenarios
    ///
    /// [onCreate] is called if the database did not exist prior to calling
    /// [openDatabase]. You can use the opportunity to create the required tables
    /// in the database according to your schema
    

    【讨论】:

    • version 到底是什么意思?
    • 这是一种帮助数据库迁移的方法。更新您的应用程序时,代码会更新,但数据库保持不变。在 onUpgrade 回调中,您也有一个 oldVersion 参数。然后你可以勾选“如果我的旧版本是2,而我的新版本是3,我需要修改这个表”
    猜你喜欢
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多