Study Record

[Flutter] 데이터베이스 importing (drift) 본문

Flutter/라이브러리

[Flutter] 데이터베이스 importing (drift)

초코초코초코 2023. 3. 26. 00:37
728x90

 

✍ 데이터베이스 importing

drift 에서 새로운 데이터 베이스를 만들지 않고 이미 있는 데이터 베이스를 importing 할 수 있다.

 

 

첫 번째로, assets 디렉터리에 데이터 베이스 파일을 넣고 pubspec.yaml 에 데이터 베이스 파일을 추가한다.

 

 

두 번째로, 데이터 베이스 클래스에 미리 생성된 데이터 베이스가 없으면 assets 에 저장한 데이터 베이스를 저장하는 걸로 importing 을 할 수 있다.

import 'package:drift/drift.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path/path.dart' as p;

LazyDatabase _openConnection() {
  return LazyDatabase(() async {
    // put the database file, called db.sqlite here, into the documents folder
    // for your app.
    final dbFolder = await getApplicationDocumentsDirectory();
    final file = File(p.join(dbFolder.path, 'app.db'));

    if (!await file.exists()) {
        // Extract the pre-populated database file from assets
        final blob = await rootBundle.load('assets/my_database.db');
        final buffer = blob.buffer;
        await file.writeAsBytes(buffer.asUint8List(blob.offsetInBytes, blob.lengthInBytes));
    }

    return NativeDatabase.createInBackground(file);
  });
}

 

 

 

 

Importing and exporting databases

Importing and exporting databases Using drift with an existing database You can use drift with a pre-propulated database that you ship with your app. This page also describes how to export the underlying sqlite3 database used by drift into a file. Using an

drift.simonbinder.eu

 

728x90