在创建数据库表之前检查数据库是否存在

时间:2019-07-28 10:08:58

标签: flutter

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的食谱中与sqlite一起使用数据库。 我认为onCreate代码不会检查dogs table。我想要的是检查桌子。例如,当我创建dogs table时,我希望dogs table已经存在。我怎么能得到?

1 个答案:

答案 0 :(得分: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