SQLite(sqflite)

이원석·2023년 11월 27일
0

Flutter

목록 보기
29/46

sqflite

flutter 앱은 pub.dev에서 제공되는 플러그인 sqflite 을 통해 SQLite 데이터베이스를 활용할 수 있다.


패키지 설치

  1. sqflite 패키지 설치
    sqflite는 SQLite 데이터베이스와 상호 작용하는 클래스와 함수를 제공
dependencies:
  sqflite: ^2.3.0
  1. path 패키지 설치
    path는 디스크에 데이터베이스를 저장할 위치를 정의하는 기능을 제공
dependencies:
  path: ^1.8.3

데이터베이스 열기

데이터베이스에서 데이터를 읽고 쓰기전에 데이터베이스에 대한 연결을 연다.
1. sqflite의 getDatabasesPath()와 path의 join함수를 사용하여 데이터베이스 파일 경로 정의
2. sqflite의 openDatabase()함수를 이용하여 데이터베이스 열기

Database? db;

  Future init() async{
     db = openDatabase(
      join(await getDatabasesPath(), 'food_database.db'),
    );
  }

테이블 생성

 Future<void> onCreateDB(Database db, int version) {
    return db.execute('''create table $tableFood ( 
  $columnId integer primary key autoincrement, 
  $columnName text not null,
  $columnPurchaseDate text not null,
  $columnExpirationDate text not null,
  $columnQuantity text not null,
  $columnUnit text not null)''');
  }
Future init() async {
    db = await openDatabase(
      join(await getDatabasesPath(), 'food_database.db'),
      onCreate: onCreateDB,
      version: 1,
    );
  }

Database변수 getter 생성

Future<Database> get database async {
    if (db != null) return db!;
    await init();
    return db!;
  }

Insert

  1. 객체를 Map으로 변환
  2. insert() 함수를 사용하여 저장
Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'purchaseDate': purchaseDate,
      'expirationDate': expirationDate,
      'quantity': quantity,
      'unit': unit,
    };
  }
Future<void> insert(Food food) async {
    final db = await database;
    await db.insert(tableFood, food.toMap());
  }

리스트 검색

  1. 쿼리 실행. List<Map> return
  2. List<Map>List<Food>로 변환.
Future<List<Food>> foods() async {
    List<Food> foods = [];
    final db = await database;

    final List<Map<String, dynamic>> maps = await db.query(tableFood);
    for (var map in maps) {
      foods.add(Food.fromJson(map));
    }
    return foods;
  }

Update

  1. Food를 Map으로 변환
  2. where절을 사용하여 update
Future<void> update(Food food) async {
    final db = await database;
    await db.update(
      tableFood,
      food.toMap(),
      where: 'id = ?',
      whereArgs: [food.id],
    );
  }

Delete

delete()을 사용하여 제거

Future<void> delete(int id) async {
    final db = await database;
    await db.delete(
      tableFood,
      where: 'id = ?',
      whereArgs: [id],
    );
  }

참조
flutter.dev

0개의 댓글