flutter中如何使用sqflite数据库?

码云
2020-11-23 18:52

flutter中可以使用sqflite存储和查询数据,具体的使用方式如下:

 

首先是数据库访问工具类DatabaseHelper:

import 'dart:io' show Directory;
import 'package:path/path.dart' show join;
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart' show getApplicationDocumentsDirectory;

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';

  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';

  //保持单例
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  //维持数据库对象的唯一引用
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  //连接数据库(如果不存在则初始化)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  //数据库初始化操作
  Future _onCreate(Database db, int version) async {
    //建立表结构
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnAge INTEGER NOT NULL
          )
          ''');

    //插入初始数据
    await db.rawInsert('INSERT INTO $table ($columnName, $columnAge) VALUES("Bob", 23)');
    await db.rawInsert('INSERT INTO $table ($columnName, $columnAge) VALUES("Mary", 32)');
    await db.rawInsert('INSERT INTO $table ($columnName, $columnAge) VALUES("Susan", 12)');
  }
}

 

工具类的使用:

_query() async {

  //获取数据库对象
  Database db = await DatabaseHelper.instance.database;

  //获取所有数据
  List<Map> result = await db.query(DatabaseHelper.table);

  //打印数据
  result.forEach((row) => print(row));
  // {_id: 1, name: Bob, age: 23}
  // {_id: 2, name: Mary, age: 32}
  // {_id: 3, name: Susan, age: 12}
}

_rawQuery() async {
  //获取数据库对象
  Database db = await DatabaseHelper.instance.database;

  //查询数据
  List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=?', ['Mary']);

  //打印结果
  result.forEach((row) => print(row));
  // {_id: 2, name: Mary, age: 32}
}

 

全部评论