Flutter数据库

481 阅读1分钟

一、数据库基础

数据库、对于一个移动端开发者,或H5开发者,都比较常见的且必须要掌握的。但是也有很多初学者概念没搞得很清楚。

1、常见的数据库有哪些

www.html.cn/qa/other/22…

zhuanlan.zhihu.com/p/40249486

2、SQLite

SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制。

Sqlite学习文档 www.runoob.com/sqlite/sqli…

SQLite入门 www.bilibili.com/video/BV1t7…

3、SQLite 和 MySQL 的区别

blog.csdn.net/qq_31930499…

从上面几节可以看出。 SQLite 实际上就是一个单机的数据库。而MySQL、 Oracle 等是一种有服务器的关系型数据库。 那我们在移动端、和windows本地使用的数据库,肯定都是SQLite。 所以我们的 sqflite (pub.dev/packages/sq…) 第三方库。肯定也是操作我们本地的 SQLite。

二、使用SQLite管理数据库

1、定义自己的 数据库管理文档

import 'package:sqflite/sqflite.dart';
import 'package:tekartik_common_utils/common_utils_import.dart';

const String dbName = 'Test.db';
const int kVersion = 1;
String tableNotes = 'localPerson';

class JCDBManager {
  late final lock = Lock(reentrant: true);
  late final DatabaseFactory dbFactory;
  Database? db;

  JCDBManager(this.dbFactory);

  Future<Database?> get ready async => db ??= await lock.synchronized(() async {
        if (db == null) {
          await open();
        }
        return db;
      });

  Future open() async {
    await openPath(await fixPath(dbName));
  }

  Future<String> fixPath(String path) async => path;

  // 创建数据库
  Future openPath(String path) async {
    db = await dbFactory.openDatabase(
        path,
        options: OpenDatabaseOptions(
            version: kVersion,
            onCreate: (db, version) async {
              print("创建数据");
              await _createDb(db);
            },
            onUpgrade: (db, oldVersion, newVersion) async {
              print(newVersion);
              if (oldVersion < kVersion) {
                print("更新数据库");
              }
            }
        )
    );
  }
   
  // 创建
  Future _createDb(Database db) async {
    await db.execute('DROP TABLE If EXISTS $tableNotes');
    await db.execute( 'CREATE TABLE $tableNotes(ID INTEGER PRIMARY KEY AUTOINCREMENT, chinese TEXT, English TEXT, Math TEXT)' );
  }
  
  // 插入
  Future insertIntoTable({required String chinaese, required String english, required String math}) async {
    await db!.execute( 'insert into $tableNotes (chinese, English, Math) values($chinaese, $english, $math)' );
  }
    
  // 查询
  Future<List<Map<String, dynamic>>> getData() async {
    List<Map<String, dynamic>> list =
    await db!.rawQuery("select * from $tableNotes");
    print(list.toString());
    return list;
  }
  
  // 删除
  Future delateDataWithId({required String ID}) async {
    await db!.execute( 'DELETE FROM $tableNotes WHERE ID = $ID' );
  }
}

2、使用数据库

_initDB() async {
    WidgetsFlutterBinding.ensureInitialized();
    platformInit();
    if (!kIsWeb) {
      sqfliteWindowsFfiInit();
    }

    var packagName = 'com.****';
    var dataFactory = getDatabaseFactory(packageName: packagName);
    dataFactory.setDatabasesPath(dbSavePath);
    dbManager = JCDBManager(dataFactory);

    await dbManager.ready;
  }

  _addData() async {
    dbManager.insertIntoTable(chinaese: "820", english: "930", math: "1010");
  }


  _getData()  async {
    print("result : " + dbManager.getData().toString());
  }

  _deleData() {
    dbManager.delateDataWithId(ID: "3");
  }

联表删除

"DELETE FROM table_2 where server_id in(select server_id from table_1 where time < $timeInterval)";