sqflite是一款轻量级的关系型数据库,类似SQLite。
使用介绍
1.首先需要在pubspec.yaml 导入库
2.新建一个model类
class UserModel {
int? id;
String name;
String height;
UserModel({
this.id,
required this.name,
required this.height,
});
factory UserModel.fromMapToModel(Map mapa) => UserModel(
id: mapa["id"],
name: mapa["name"],
height: mapa["height"],
);
factory UserModel.fromJson(Map mapa) => UserModel(
id: mapa["id"],
name: mapa["name"],
height: mapa["height"],
);
Map toJson() => {
"id": id,
"name": name,
"height": height,
};
}
3.创建一个DB_Manager
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sql_demo/database/user_model.dart';
class DBManager {
Database? myDatabase;
String tableName = 'mytable';
static final DBManager db = DBManager._();
DBManager._();
Future getCheckDatabase() async {
if (myDatabase != null) return myDatabase;
myDatabase = await initDB();
return myDatabase;
}
Future initDB() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, 'MYDB.db');
print(path);
return await openDatabase(path, version: 1, onOpen: (db) {},
onCreate: (Database db, int v) async {
await db.execute(
"CREATE TABLE $tableName(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, height TEXT)");
});
}
Future getDBInfo() async {
final Database? databaseDB = await getCheckDatabase();
List res =
await databaseDB!.query("SELECT * FROM $tableName ORDER BY id DESC");
return res;
}
// 获取所有用户
Future> getUsers() async {
List res = [];
final Database? databaseDB = await getCheckDatabase();
// print(222);
List getRes = await databaseDB!.query(tableName, orderBy: 'id DESC');
// getRes = getRes.reversed.toList();
// getRes.forEach((element) {
// res.add(UserModel.fromMapToModel(element));
// });
res = getRes.map((e) => UserModel.fromMapToModel(e)).toList();
return res;
}
customInsetSqlStr(String sqlStr) async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!.rawInsert(sqlStr);
print('执行结果$res');
}
// 执行表得插入
insertToTab() async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!.rawInsert(
"INSERT INTO $tableName(name,height) VALUES('No Pain, No Gain','J. L. D. Barnett')");
print('执行结果$res');
}
insertUser(UserModel user) async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!.insert(tableName, user.toJson());
// {
// "name":user.name,
// "height":user.height,
// }
//(res!=null) ? inserted=true: inserted=false;
print('执行结果$res');
}
// 更新表操作
Future updataTableRaw(UserModel user) async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!.rawUpdate(
"UPDATE $tableName SET name = ${user.name}, author = ${user.height} WHERE id = ${user.id}");
return res;
}
// 更新用户
updataUser(UserModel user) async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!
.update(tableName, user.toJson(), where: "id = ${user.id}");
print('执行结果$res');
}
Future deleteTableRaw(int userId) async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!
.rawDelete("DELETE FROM $tableName WHERE id = $userId");
return res;
}
deletaUser(int userId) async {
final Database? databaseDB = await getCheckDatabase();
int res = await databaseDB!.delete(tableName, where: "id = $userId");
print('执行结果$res');
}
}
4.开始使用
DBManager.db.getUsers().then((value) {
users = value;
setState(() {});
});
DBManager.db.insertToTab();
setState(() {
getUserList();
});