Reputation: 393
I have been searching to import csv to database in flutter way. But unfortunately, I cannot find articles related to this case. So I wonder if there is a way to import csv to database. If yes, how can I achieve that? For my case, I open the file picker and want to import csv file. I can easily do it in Kotlin way but not in a flutter way. I would appreciate any help.
Upvotes: 3
Views: 4092
Reputation: 1714
Well, it's not straightforward.
You'd normally use something like https://pub.dev/packages/csv or https://pub.dev/packages/spreadsheet_decoder in order to parse CSV.
So it'd look something like:
final input = new File('documents/file.csv').openRead();
Then convert it to the list:
final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();
After you did that, you'd normally have a function that is going to do a bulk update.
First, create a database
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
Then you could use some helper method like mentioned here => https://stackoverflow.com/a/56507307/1737811 in order to populate the database fields with your result.
That way you'd pass your tablename
, and of course your List
containing the values from the CSV that you've just decoded.
Upvotes: 6