1.创建初始化数据库类
db_init.dart
import 'package:sqflite/sqlite_api.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'package:path/path.dart';//path是必须映入的一个库,用户拼接数据库地址,很好的解决了兼容性问题
class SqlManager {
static const _VERSION = 1;
static const _NAME = 'test.db';
static Database _database;
// 初始化数据库
static init()async{
var databasePath = await getDatabasesPath();
String path = join(databasePath,_NAME);
_database = await openDatabase(path,version: _VERSION);
}
// 判断表是否存在
static Future<bool> isTableExits(String tableName) async {
await getCurrentDatabase();
var res = await _database.rawQuery("select * from Sqlite_master where type = 'table' and name = '$tableName'");
return res != null && res.length>0;
}
// 获取数据库(返回当前实例,还是重新初始化)
static Future<Database> getCurrentDatabase() async {
if(_database == null){
await init();
}
return _database;
}
// 关闭数据库
static close(){
_database?.close();
_database = null;
}
}
2.创建基类TableBase
描述:TableBase是一个抽象类(抽象类只能被继承,不能被实现),规定你所有关于表的类,都必须继承这个基类,也是一个规范
import 'package:flutter/material.dart';
import 'package:app/db/db_init.dart';
import 'package:sqflite/sqlite_api.dart';
import 'package:sqflite/sqflite.dart';
abstract class TableBase {
bool isTableExits = false;//给定一个初始值是为了,避免重复获取数据库实例
createTableString();//无函数体的子类必须实现(创建表的sql语句)
tableName();//无函数体的子类必须实现(返回表的名字)
///创建表sql语句
tableBaseString(String sql) {
return sql;
}
// 获取数据库实例
Future<Database> getDataBase() async {
return await open();
}
///判断有没有表,有表及返回当前数据库
@mustCallSuper
open() async {
if (!isTableExits) {
await prepare(tableName(), createTableString());
}
return await SqlManager.getCurrentDatabase();
}
///没有表要进行创建表,并且返回有当前表的数据库实例
@mustCallSuper
prepare(name, String createSql) async {
isTableExits = await SqlManager.isTableExits(name);
if (!isTableExits) {
Database db = await SqlManager.getCurrentDatabase();
return await db.execute(createSql);
}
}
}
3.基础的写好了,接下来我们看看该怎么使用(此处描述了Person表和Person的使用)
import 'package:app/db/table_base.dart';
import 'package:app/model/user/user_model.dart';
import 'package:sqflite/sqlite_api.dart';
import 'package:sqflite/sqflite.dart';
class PersonDbProvider extends TableBase {
///表信息(每个表里面的字段你都要在上面定义,name是基类里面必须实现的,剩下的就是表里面的字段)
final String name = 'PresonInfo';
final String columnId = "id";
final String columnMobile = "mobile";
final String columnHeadImage = "headImage";
// 查看表名
@override
tableName() {
return name;
}
// 创建表的sql语句
@override
createTableString() {
return '''
create table $name (
$columnId integer primary key,
$columnHeadImage text not null,
$columnMobile text not null
)
''';
}
///插入到数据库
Future insert(UserModel model) async {
Database db = await getDataBase();//首先获取数据库实例
var userProvider = await select(id:model.id);//避免重复插入,select方法的实现在下面
if (userProvider != null) {
///删除数据
await db.delete(name, where: "$columnId = ?", whereArgs: [model.id]);
}
return await db.rawInsert(
"insert into $name ($columnId,$columnMobile,$columnHeadImage) values (?,?,?)",
[model.id, model.mobile, model.headImage]);
}
// 查询personInfo表
Future select({int id, String tableName}) async {
if (id != null) {
Database db = await getDataBase();
List<Map<String, dynamic>> maps =
await db.rawQuery('select * from $name where $columnId = $id');
return maps;
} else {
Database db = await getDataBase();
List<Map<String, dynamic>> maps = await db.query(tableName);
return maps;
}
}
// ///更新数据库
// Future<void> update(UserModel model) async {
// Database database = await getDataBase();
// await database.rawUpdate(
// "update $name set $columnMobile = ?,$columnHeadImage = ? where $columnId= ?",[model.mobile,model.headImage,model.id]);
// }
// ///获取事件数据
// Future<UserModel> getPersonInfo(int id) async {
// Database db = await getDataBase();
// List<Map<String, dynamic>> maps = await _getPersonProvider(db, id);
// if (maps.length > 0) {
// return UserModel.fromJson(maps[0]);
// }
// return null;
// }
}
class PersonOperation {
///用户信息插入数据库
Future insert() async {
PersonDbProvider provider = PersonDbProvider();
UserModel userModel = UserModel();
userModel.name = '杨志强';
userModel.age = 12;
userModel.headImage = 'http://baidu.com';
userModel.id = 1;
userModel.sex = false;
userModel.mobile = 15735090985;
provider.insert(userModel);
}
Future insert2() async {
PersonDbProvider provider = PersonDbProvider();
UserModel userModel = UserModel();
userModel.name = '杨志强';
userModel.age = 12;
userModel.headImage = 'http://baidu.com';
userModel.id = 2;
userModel.sex = false;
userModel.mobile = 15735090985;
provider.insert(userModel);
}
// 获取表中某一条数据示例
Future<List<Map<String, dynamic>>> select() async {
PersonDbProvider provider = PersonDbProvider();
var data = await provider.select(id: 1);
return data;
}
// 获取表中的所有数据
Future<List<Map<String, dynamic>>> selectAll() async {
PersonDbProvider provider = PersonDbProvider();
var data = await provider.select(tableName: provider.tableName());
return data;
}
}
网友评论