Sub topic 8
Insert, query, update and delete safely
This chapter covers the four basic database operations in sqflite and how to run them without opening your app to SQL injection or silent data bugs. It assumes you can open a database as shown in the previous chapter, that you have the Note class with toMap and fromMap, and that you are comfortable with async and await.
Why parameters matter
SQL injection happens when user input is pasted into SQL text and the database cannot tell the data from the commands. A local SQLite file is not a server, but the risk is still real. A search box, a deep link or an imported file can all supply hostile text. Even without an attacker, a note titled Bob's list breaks a query built with string interpolation, because the apostrophe ends the string early.
// Unsafe: the title becomes part of the SQL text.
Future<List<Map<String, Object?>>> unsafeSearch(Database db, String title) {
return db.rawQuery("SELECT * FROM notes WHERE title = '$title'");
}If title is ' OR '1'='1, this query returns every row. The fix is to put a ? placeholder in the SQL and pass the values separately. SQLite then receives the SQL and the values as two separate things, so a value can never be read as SQL.
Insert
db.insert takes a table name and a map of column names to values. It returns the rowid of the new row, which for an INTEGER PRIMARY KEY column is the id.
import 'package:sqflite/sqflite.dart';
Future<int> insertNote(Database db, Note note) {
return db.insert(
'notes',
note.toMap()..remove('id'),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}The id key is removed so SQLite assigns the next one itself. If you left 'id': null in the map, SQLite would still generate a value, but removing the key makes the intent clear.
The conflictAlgorithm decides what happens when the insert would break a constraint, such as a duplicate primary key or a unique column. The options differ in important ways:
| Algorithm | Behavior on conflict |
|---|---|
| `abort` (default) | Cancels this statement and throws a `DatabaseException`. |
| `replace` | Deletes the existing conflicting row, then inserts the new one. |
| `ignore` | Skips the insert and does not throw. The returned id is 0. |
| `fail` | Throws, but keeps changes the statement already made. |
| `rollback` | Throws and rolls back the whole current transaction. |
replace deletes and re-inserts. That means columns you did not include in the map reset to their defaults, and foreign keys that point to the old row may break. For a simple notes table it is convenient. For anything with relationships, prefer abort and handle the error, or use an explicit update.
Query
db.query builds a SELECT for you. Every part that carries a value uses placeholders.
Future<List<Note>> searchNotes(Database db, String title) async {
final rows = await db.query(
'notes',
where: 'title = ?',
whereArgs: [title],
);
return rows.map(Note.fromMap).toList();
}
Future<List<Note>> latestNotes(Database db, {int count = 20}) async {
final rows = await db.query(
'notes',
columns: ['id', 'title', 'body'],
orderBy: 'id DESC',
limit: count,
);
return rows.map(Note.fromMap).toList();
}The result is a List<Map<String, Object?>>, one map per row. The maps are read-only, so copy one with Map.of(row) if you need to change it. columns limits which columns are fetched, which matters once rows hold large text or blobs.
Searching with LIKE
Wildcards belong in the argument, not in the SQL text:
Future<List<Note>> searchByText(Database db, String text) async {
final rows = await db.query(
'notes',
where: 'title LIKE ?',
whereArgs: ['%$text%'],
orderBy: 'title',
limit: 50,
);
return rows.map(Note.fromMap).toList();
}Interpolating into the argument is safe, because the whole string is bound as one value. One side effect remains. A % or _ typed by the user acts as a wildcard inside the pattern. For a notes search this is usually acceptable. If it is not, add ESCAPE '\' to the SQL and escape those characters in the text.
IN lists
A placeholder stands for one value, not a list. Generate one ? per item and pass the items in whereArgs:
Future<List<Note>> notesByIds(Database db, List<int> ids) async {
if (ids.isEmpty) return [];
final placeholders = List.filled(ids.length, '?').join(', ');
final rows = await db.query(
'notes',
where: 'id IN ($placeholders)',
whereArgs: ids,
);
return rows.map(Note.fromMap).toList();
}Only the count of placeholders is interpolated, never the values. SQLite limits the number of variables per statement (999 in older versions), so split very long lists into chunks.
Raw queries
When query is not enough, for example with joins or aggregates, use rawQuery with placeholders and whereArgs-style arguments:
Future<int> countNotes(Database db, String prefix) async {
final result = await db.rawQuery(
'SELECT COUNT(*) FROM notes WHERE title LIKE ?',
['$prefix%'],
);
return Sqflite.firstIntValue(result) ?? 0;
}Update and delete
update and delete both return the number of rows they changed. Use that number. A return value of 0 means nothing matched your where clause.
Future<int> updateNote(Database db, Note note) {
final id = note.id;
if (id == null) {
throw ArgumentError('Cannot update a note that has no id.');
}
return db.update(
'notes',
note.toMap()..remove('id'),
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> deleteNote(Database db, int id) {
return db.delete('notes', where: 'id = ?', whereArgs: [id]);
}Value types and NULL
Binding has a few rules that cause most beginner bugs.
- Allowed types. SQLite stores integers, floating-point numbers, text and blobs. Values passed to sqflite must be
int,double,String,Uint8Listornull. AboolorDateTimethrows an error. - Booleans. Store them as
0and1in anINTEGERcolumn. Convert intoMap(pinned ? 1 : 0) and infromMap(map['pinned'] == 1). - Dates. Store an ISO 8601 string from
toIso8601String()or an integer frommillisecondsSinceEpoch. Both sort correctly. Pick one and use it everywhere. - NULL. In SQL,
body = NULLnever matches anything, even rows wherebodyis null. Writebody IS NULLinstead. If your argument can be null, choose the clause in Dart.
Future<List<Note>> notesWithBody(Database db, {required bool hasBody}) async {
final rows = await db.query(
'notes',
where: hasBody ? 'body IS NOT NULL' : 'body IS NULL',
);
return rows.map(Note.fromMap).toList();
}- Names are not parameters. Table and column names cannot be placeholders. If a column name comes from outside, such as a sort option, map it through a fixed list of allowed names in Dart. Never interpolate raw input into
orderBy.
const _sortColumns = {'title', 'id'};
Future<List<Note>> sortedNotes(Database db, String sortBy) async {
final column = _sortColumns.contains(sortBy) ? sortBy : 'id';
final rows = await db.query('notes', orderBy: column);
return rows.map(Note.fromMap).toList();
}Transactions and batches
Each call on db is its own statement. If a task needs several writes that must all succeed or all fail, group them in a transaction. If any statement throws, SQLite rolls back everything done inside it.
Future<void> moveBody(Database db, int fromId, int toId) {
return db.transaction((txn) async {
final rows = await txn.query(
'notes',
columns: ['body'],
where: 'id = ?',
whereArgs: [fromId],
);
if (rows.isEmpty) throw StateError('Note $fromId not found.');
await txn.update(
'notes',
{'body': rows.first['body']},
where: 'id = ?',
whereArgs: [toId],
);
await txn.update(
'notes',
{'body': null},
where: 'id = ?',
whereArgs: [fromId],
);
});
}Inside the callback, always use txn, not db. Calling db from inside a transaction waits for the transaction to finish, which never happens, so the app hangs.
For many similar writes, a Batch queues the operations and sends them together. This is much faster than awaiting each insert in a loop, and commit runs it in a transaction by default.
Future<void> insertMany(Database db, List<Note> notes) async {
final batch = db.batch();
for (final note in notes) {
batch.insert('notes', note.toMap()..remove('id'));
}
await batch.commit(noResult: true);
}noResult: true skips collecting the per-operation results, which saves memory on large batches.
Common mistakes
- Building SQL by interpolating values instead of using
?. - Forgetting that
updateanddeleteneed awhereclause, or ignoring the returned count. - Passing a
boolorDateTimeinwhereArgs. - Using
= ?with a null value instead ofIS NULL. - Using
dbinstead oftxninside a transaction. - Using
ConflictAlgorithm.replaceon tables with related rows, which deletes the old row first.
Exercise
A user types the search text 50% into your notes search. Your code runs db.query('notes', where: 'title LIKE ?', whereArgs: ['%$text%']). Is this open to SQL injection? What unexpected behavior can still happen, and how would you handle it?
Show answer
It is not open to SQL injection, because the whole string %50%% is bound as a single value and never parsed as SQL. The remaining issue is that % inside the text is a LIKE wildcard, so the pattern matches more titles than the user meant. To treat it literally, escape %, _ and the escape character in the text (for example with a backslash) and add ESCAPE '\' to the SQL, as in where: "title LIKE ? ESCAPE '\\'".
Exercise
db.update('notes', {'title': 'Draft'}, where: 'id = ?', whereArgs: [42]) returns 0. What does that mean, and how should your repository code respond?
Show answer
It means no row has id 42, so nothing was changed. The statement itself did not fail. The repository should check the returned count and report the problem, for example by throwing a not-found error or returning false, instead of assuming the update worked.