Flutter 数据库简单使用

2019-12-30  本文已影响0人  地选之猿

最近在学习flutter中的数据库操作,这篇博客用来记录学习中的一些成果,方便以后查阅.
参考文章:https://www.jianshu.com/p/0850c80a373c

安装库

  sqflite: ^1.1.0

在pubspec.yaml中配置上面内容,在终端输入

flutter pub get

获取库内容,在要使用的地方导入库

import 'package:sqflite/sqflite.dart';

此时,就可以使用该库了.

创建数据库及建表

String sql_createAccountTable = "create table account_table(id integer primary key, username text not null, password text not null)";
Future<String> _createNewDb(String dbName) async {
    var dbPath = await getDatabasesPath();
    print("DBPath:" + dbPath);

    String path = join(dbPath, dbName);
    if (await new Directory(dirname(path)).exists()) {
      await deleteDatabase(path);
    }else {
      try {
        await new Directory(dirname(path)).create(recursive: true);
      } catch(e) {
        print(e);
      }
    }
    return path;
}
_create() async {
    dbPath = await _createNewDb(dbName);
    Database db = await openDatabase(dbPath);
    await db.execute(sql_createAccountTable);
    await db.close();
    print("创建数据库成功");
}

创建成功后,再写一个获取数据库的方法,方便每次对数据库的操作

_open() async {
    if (null == dbPath) {
      var path = await getDatabasesPath();
      dbPath = join(path, dbName);
      print('dbPath:'+dbPath);
    }

    return await openDatabase(dbPath);
}

增/删/改/查

 _add(String username, String password) async {
    Database db = await _open();
    String sql = "insert into account_table(username,password) values('$username', '$password')";
    await db.transaction((txn) async {
      int id = await txn.rawInsert(sql);
    });
    await db.close();
    print('插入数据成功');
    _refresh();
}

_delete(Map info) async {
    var id = info["id"];
    Database db = await _open();
    String sql = "DELETE FROM account_table where id = $id";
    await db.rawDelete(sql);
    await db.close();
    print('删除数据成功');
    _refresh();
}

_update(int id, String account, String pwd) async {
    Database db = await _open();
    String sql = "Update account_table set password = ?, username = ? where id = ?";
    int count = await db.rawUpdate(sql, [pwd, account, id]);
    await db.close();
    print('更新数据成功');
    _refresh();
}

//查询数据数目
_queryNumber() async {
    Database db = await _open();
    int count = Sqflite.firstIntValue(await db.rawQuery("select COUNT(*) from account_table"));
    await db.close();
    print("查询数据成功 $count");
    setState(() {
      _cnt = count;
    });
}

//查询所有数据
Future<List> _query() async {
    Database db = await _open();
    List<Map> list = await db.rawQuery("select * from account_table");
    await db.close();
    print(list);
    return list;
}

批量操作

_batch() async {
    Database db = await _open();
    var batch = db.batch();
    batch.insert("account_table", {"username":"123450002", "password":"111"});
    batch.update("account_table", {"username":"123450003"}, where: "username=?", whereArgs: ["123450002"]);
    batch.delete("account_table", where: "username=?", whereArgs: ["123450001"]);
    var results = await batch.commit();
    await db.close();
    print('批量修改成功');
    _refresh();
}

总结

至此,flutter中数据库的基本操作都已经尝试完毕.记住每步操作都要加上await关键字.
完整Demo地址

上一篇下一篇

猜你喜欢

热点阅读