Flutter sqflite插件

发布于:2025-08-15 ⋅ 阅读:(14) ⋅ 点赞:(0)

数据库插件

dependencies:
  sqflite: ^2.4.2

请添加图片描述

class MyState extends State {
  String dbPath = "";
  Database? database;

  ///获取数据库路径
  void getDBPath() {
    Future<String> path = getDatabasesPath();
    path.then((value) {
      dbPath = value;
      print(value);
    });
  }

  void initDB() {
    //如果没有word数据库,则会调用onCreate方法创建数据库。
    Future<Database> db = openDatabase(
      version: 2,
      "$dbPath/word.db",
      onCreate: (db, version) {
        String createSql =
            'CREATE TABLE "word" ("id" integer PRIMARY KEY AUTOINCREMENT,"def" text,"pron" text,"word" text)';
        db.execute(createSql);
      },
      onUpgrade: (db, oldVersion, newVersion) {
        //当前版本大于原版本,则执行
        if (newVersion >= 2) {
          db.execute("ALTER TABLE word ADD COLUMN collect integer");
        }
        print("$oldVersion,$newVersion");
      },
    );
    db.then((value) {
      database = value;
      print(value);
    });
  }

  
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 5,
      child: Scaffold(
        appBar: AppBar(title: Text("购物")),
        body: Column(
          children: [
            OutlinedButton(
              onPressed: () {
                getDBPath();
              },
              child: Text("获取数据库路径"),
            ),
            OutlinedButton(
              onPressed: () {
                initDB();
              },
              child: Text("初始化数据库"),
            ),
            OutlinedButton(
              onPressed: () {
                if (database == null) {
                  initDB();
                } else {
                  Future<int>? add = database?.rawInsert(
                    'INSERT INTO word(id, def, pron, word) VALUES (?,?,?,?)',
                    [2, "抛弃;放纵", " əˈbændənmənt", "abandonment"],
                  );
                  add?.then((value) {
                    print("添加数据的id:$value");
                  });
                }
              },
              child: Text("插入数据"),
            ),
            OutlinedButton(
              onPressed: () {
                if (database == null) {
                  initDB();
                } else {
                  Future<int>? add = database?.rawUpdate(
                    'update word set collect = ? where id = ?',
                    [1, 2],
                  );
                  add?.then((value) {
                    print("修改了$value条");
                  });
                }
              },
              child: Text("修改数据"),
            ),
            OutlinedButton(
              onPressed: () {
                if (database == null) {
                  initDB();
                } else {
                  Future<List<Map<String, Object?>>>? qu = database?.rawQuery(
                    'select * from word where id = ?',
                    [2],
                  );
                  qu?.then((value) {
                    print("查询数据:$value");
                  });
                }
              },
              child: Text("查询数据"),
            ),
            OutlinedButton(
              onPressed: () {
                if (database == null) {
                  initDB();
                } else {
                  Future<int>? del = database?.rawDelete(
                    'delete from word where id = ?',
                    [2],
                  );
                  del?.then((value) {
                    print("删除了$value条");
                  });
                }
              },
              child: Text("删除数据"),
            ),
          ],
        ),
      ),
    );
  }
}

直接使用db文件的情况

    File file = File("$path/school.db");
    rootBundle.load("assert/db/school.db").then((value) {

      file.writeAsBytes(value.buffer.asUint8List());
    },);
   Future<Database> db = openDatabas("$path/school.db");