sqflite model code example
Example 1: delete query in sqlite flutter
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
// Delete the database
await deleteDatabase(path);
// open the database
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// When creating the db, create the table
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
// Insert some records in a transaction
await database.transaction((txn) async {
int id1 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
print('inserted1: $id1');
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
print('inserted2: $id2');
});
// Update some record
int count = await database.rawUpdate(
'UPDATE Test SET name = ?, value = ? WHERE name = ?',
['updated name', '9876', 'some name']);
print('updated: $count');
// Get the records
List
Example 2: flutter sqflite DatabaseHelper
class Todo{
int id;
String itemName;
String dateCreated;
Todo(
{this.id,
this.itemName,
this.dateCreated})
//to be used when inserting a row in the table
Map toMapWithoutId() {
final map = new Map();
map["item_name"] = itemName;
map["date_created"] = dateCreated;
return map;
}
Map toMap() {
final map = new Map();
map["id"] = id;
map["item_name"] = itemName;
map["date_created"] = dateCreated;
return map;
}
//to be used when converting the row into object
factory Todo.fromMap(Map data) => new Todo(
id: data['id'],
itemName: data['item_name'],
dateCreated: data['date_created']
);
}