最近在學(xué)習(xí)flutter中的數(shù)據(jù)庫操作,這篇博客用來記錄學(xué)習(xí)中的一些成果,方便以后查閱.
參考文章:http://www.reibang.com/p/0850c80a373c
安裝庫
sqflite: ^1.1.0
在pubspec.yaml中配置上面內(nèi)容,在終端輸入
flutter pub get
獲取庫內(nèi)容,在要使用的地方導(dǎo)入庫
import 'package:sqflite/sqflite.dart';
此時,就可以使用該庫了.
創(chuàng)建數(shù)據(jù)庫及建表
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("創(chuàng)建數(shù)據(jù)庫成功");
}
創(chuàng)建成功后,再寫一個獲取數(shù)據(jù)庫的方法,方便每次對數(shù)據(jù)庫的操作
_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('插入數(shù)據(jù)成功');
_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('刪除數(shù)據(jù)成功');
_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('更新數(shù)據(jù)成功');
_refresh();
}
查
//查詢數(shù)據(jù)數(shù)目
_queryNumber() async {
Database db = await _open();
int count = Sqflite.firstIntValue(await db.rawQuery("select COUNT(*) from account_table"));
await db.close();
print("查詢數(shù)據(jù)成功 $count");
setState(() {
_cnt = count;
});
}
//查詢所有數(shù)據(jù)
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();
}
總結(jié)
至此,flutter中數(shù)據(jù)庫的基本操作都已經(jīng)嘗試完畢.記住每步操作都要加上await關(guān)鍵字.
完整Demo地址