Flutter sqflite的使用-模型插入

前言

sqflite是一款輕量級(jí)的數(shù)據(jù)庫(kù),類(lèi)似SQLite.
在Flutter平臺(tái)我們使用sqflite庫(kù)來(lái)同時(shí)支持Android 和iOS.
sqflite同時(shí)可以支持表結(jié)構(gòu)升級(jí).但是本篇不介紹表結(jié)構(gòu)升級(jí),而是使用整個(gè)模型插入方式實(shí)現(xiàn)。
表結(jié)構(gòu)升級(jí)請(qǐng)點(diǎn)擊點(diǎn)我

pubspec.yaml 導(dǎo)入庫(kù)
#數(shù)據(jù)庫(kù)
sqflite: ^1.3.0
#路徑
path_provider: ^1.5.0

1、字段命名

final _version = 1;//數(shù)據(jù)庫(kù)版本號(hào)
final _name = "DataBase.db";//數(shù)據(jù)庫(kù)名稱(chēng)
final _tableUser = "tableUser";//表名稱(chēng)
final _primaryId   = "primaryId";//主鍵
final _data        = "data”;//模型內(nèi)容

2、創(chuàng)建數(shù)據(jù)庫(kù)、創(chuàng)建表

ATQueueData.internal();
//數(shù)據(jù)庫(kù)句柄
static Database _database;
Future<Database> get database async {
  print("create database");
  if (_database == null) {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, _name);
    _database =  await openDatabase(path,version: _version);
    _createTable(_database);
    print("create database success");
  }
  return _database;
}
//創(chuàng)建表
void _createTable(Database db) async{
  final sql = '''create table if not exists $_tableUser ($_primaryId integer primary key,$_data text)''';
  var batch = db.batch();
  batch.execute(sql);
  await batch.commit();
}

3、打開(kāi)、關(guān)閉表

//打開(kāi)
Future<Database> open() async{
  return await database;
}
///關(guān)閉
Future<void> close() async {
  var db = await database;
  return db.close();
}

4、插入數(shù)據(jù)

static Future insertData(int userId,String content) async{
  print(content);
  Database db = await ATQueueData.internal().open();
  db.transaction((txn) async{
    txn.rawInsert("insert or replace into $_tableUser ($_primaryId,$_data) values (?,?)",[userId,content]);
  });
  await db.batch().commit();
}

5、更新數(shù)據(jù)

static Future updateData(int userId,String content) async{
  Database db = await ATQueueData.internal().open();
  db.transaction((txn) async{
    txn.rawUpdate("update $_tableUser set $_data =  ? where $_primaryId = ?",[content,userId]);
  });
  await db.batch().commit();
}

6、刪除數(shù)據(jù)

static Future deleteData(int userId) async{
  Database db = await ATQueueData.internal().open();
  db.transaction((txn) async{
    txn.rawDelete("delete from $_tableUser where $_primaryId = ?",[userId]);
  });
  await db.batch().commit();
}

7、查詢(xún)數(shù)據(jù)

  static Future<Map> searchData(int userId) async {
    Database db = await ATQueueData.internal().open();
    List<Map<String, dynamic>> maps = await db.rawQuery("select * from $_table where $_primaryId = $userId");
    List datas = await decodeData(maps);
    return datas.first;
  }
  static Future<List> searchDatas() async {
    Database db = await ATQueueData.internal().open();
    List<Map<String, dynamic>> maps = await db.rawQuery("select * from $_tableUser");
    return await decodeData(maps);
  }
  static  Future<List> searchDataSize(int page,int size) async {
    Database db = await ATQueueData.internal().open();
    List<Map<String, dynamic>> maps = await db.rawQuery("select * from $_table order by $_primaryId asc limit ?,?",[(page - 1) * size,size]);
    return await decodeData(maps);
  }
  static Future<List> decodeData(List listData) async{
    List datas = List();
    listData.forEach((element) {
      var params = element["$_data"];
      datas.add(params);
    });
    return await datas;
  }

7、使用方式

//增
ATUser user = ATUser(userId: 10001,nickName: "呂布",mobile: "15160023363",sex: "男",age: 40);
ATQueueData.insertData(user.userId, user.toJson().toString());
//刪
ATQueueData.deleteData(10000);
//改
ATUser user = ATUser(userId: 10000,nickName: "諸葛亮春福",mobile: "15280592811",sex: "男",age: 50);
ATQueueData.updateData(10000, user.toJson().toString());
//查
ATQueueData.searchDatas()

8、ATUser類(lèi)的定義

class ATUser{
  int userId;
  String nickName;
  String mobile;
  String sex;
  int age;
  ATUser({this.userId, this.nickName, this.mobile, this.sex,this.age});
  ATUser.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    age = json['age'];
    nickName = json['nickName'];
    mobile = json['mobile'];
    sex = json['sex'];
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['userId'] = this.userId;
    data['age'] = this.age;
    data['nickName'] = this.nickName;
    data['mobile'] = this.mobile;
    data['sex'] = this.sex;
    return data;
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容