flutter 插件 sqflite


Flutter的SQLite插件。支持iOS和Android。

  • 支持交易和批次打开期间
  • 自动版本管理
  • 插入/查询/更新/删除查询的助手
  • 在iOS和Android上的后台线程中执行数据库操作

添加依赖

dependencies:
  sqflite: ^1.1.1

安装

flutter packages get

导入

import 'package:sqflite/sqflite.dart';

原生SQL查询

// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

// Delete the database
await deleteDatabase(path);

// open the database
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
      ['another name', 12345678, 3.1416]);
  print('inserted2: $id2');
});

// Update some record
int count = await database.rawUpdate(
    'UPDATE Test SET name = ?, VALUE = ? WHERE name = ?',
    ['updated name', '9876', 'some name']);
print('updated: $count');

// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
List<Map> expectedList = [
  {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
  {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
];
print(list);
print(expectedList);
assert(const DeepCollectionEquality().equals(list, expectedList));

// Count the records
count = Sqflite
    .firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
assert(count == 2);

// Delete a record
count = await database
    .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
assert(count == 1);

// Close the database
await database.close();

SQL helpers

final String tableTodo = 'todo';
final String columnId = '_id';
final String columnTitle = 'title';
final String columnDone = 'done';

class Todo {
  int id;
  String title;
  bool done;

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      columnTitle: title,
      columnDone: done == true ? 1 : 0
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }

  Todo();

  Todo.fromMap(Map<String, dynamic> map) {
    id = map[columnId];
    title = map[columnTitle];
    done = map[columnDone] == 1;
  }
}

class TodoProvider {
  Database db;

  Future open(String path) async {
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute('''
create table $tableTodo (
  $columnId integer primary key autoincrement,
  $columnTitle text not null,
  $columnDone integer not null)
''');
    });
  }

  Future<Todo> insert(Todo todo) async {
    todo.id = await db.insert(tableTodo, todo.toMap());
    return todo;
  }

  Future<Todo> getTodo(int id) async {
    List<Map> maps = await db.query(tableTodo,
        columns: [columnId, columnDone, columnTitle],
        where: '$columnId = ?',
        whereArgs: [id]);
    if (maps.length > 0) {
      return Todo.fromMap(maps.first);
    }
    return null;
  }

  Future<int> delete(int id) async {
    return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<int> update(Todo todo) async {
    return await db.update(tableTodo, todo.toMap(),
        where: '$columnId = ?', whereArgs: [todo.id]);
  }

  Future close() async => db.close();
}

读结果

假设以下读取结果:

List<Map<String, dynamic>> records = await db.query('my_table');

结果映射项是只读

// get the first record
Map<String, dynamic> mapRead = records.first;
// Update it in memory...this will throw an exception
mapRead['my_column'] = 1;
// Crash... `mapRead` is read-only

如果想在内存中修改,需要创建一个新的映射

// get the first record
Map<String, dynamic> map = Map<String, dynamic>.from(mapRead);
// Update it in memory now
map['my_column'] = 1;

事务

不要使用数据库,而只使用事务中的Transaction对象来访问数据库

await database.transaction((txn) async {
  // Ok
  await txn.execute('CREATE TABLE Test1 (id INTEGER PRIMARY KEY)');

  // DON'T  use the database object in a transaction
  // this will deadlock!
  await database.execute('CREATE TABLE Test2 (id INTEGER PRIMARY KEY)');
});

如果回调没有引发错误,则提交事务。如果抛出错误,则取消该事务。因此,以一种方式回滚事务就是抛出异常。

批量支持

要避免使用dart和本机代码之间的乒乓,可以使用Batch:

batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();

获取每个操作的结果都有成本(插入ID和更新和删除的更改次数),尤其是在执行额外SQL请求的Android上。如果您不关心结果并担心大批量的性能,您可以使用

await batch.commit(noResult: true);

警告,在事务期间,在提交事务之前不会提交批处理

await database.transaction((txn) async {
  var batch = txn.batch();

  // ...

  // commit but the actual commit will happen when the transaction is committed
  // however the data is available in this transaction
  await batch.commit();

  //  ...
});

默认情况下,批处理在遇到错误时会立即停止(通常会还原未提交的更改)。您可以忽略错误,以便即使一个操作失败也会运行并提交每个成功的操作:

await batch.commit(continueOnError: true);

表和列名称

通常,最好避免将SQLite关键字用于实体名称。如果使用以下任何名称:

"add","all","alter","and","as","autoincrement","between","case","check","collate","commit","constraint","create","default","deferrable","delete","distinct","drop","else","escape","except","exists","foreign","from","group","having","if","in","index","insert","intersect","into","is","isnull","join","limit","not","notnull","null","on","or","order","primary","references","select","set","table","then","to","transaction","union","unique","update","using","values","when","where"

助手将逃脱名称,即

db.query('table')

将等同于在表名周围手动添加双引号(这里容易引起混淆的表)

db.rawQuery('SELECT * FROM "table"');

但是在任何其他原始语句(包括orderBy,where,groupBy)中,请确保使用双引号正确地转义名称。例如,请参阅下面的列名称组未在columns参数中进行转义,但在where参数中进行转义。

db.query('table', columns: ['group'], where: '"group" = ?', whereArgs: ['my_group']);

支持的SQLite类型

DateTime不是受支持的SQLite类型。我个人将它们存储为int(millisSinceEpoch)或字符串(iso8601)

bool不是受支持的SQLite类型。使用INTEGER和0和1值。

  • INTEGER

Dart type: int

Supported values: from -2^63 to 2^63 - 1

  • REAL

Dart type: num

  • TEXT

Dart type: String

  • BLOB

Dart type: Uint8List

Dart type List is supported but not recommended (slow conversion)