Query a specific cell of sqflite data table in Flutter - flutter

There are already some questions and answers like "query a specific row". But I want a specific cell that means I need a specific row with a specific column from the sqflite data table in Flutter. My table has three columns which are id, fname, fid. But I need only fid. Here is my row selection code:
queryfid() async {
Database db = await DatabaseHelper.instance.database;
List<String> columnsToSelect = [
DatabaseHelper.columnId,
DatabaseHelper.columnfname,
DatabaseHelper.columnfid,
];
String whereString = '${DatabaseHelper.columnId} = ?';
int rowId = 1;
List<dynamic> whereArguments = [rowId];
List<Map> result = await db.query(DatabaseHelper.tableid,
columns: columnsToSelect,
where: whereString,
whereArgs: whereArguments);
result.forEach((row) => print(row));
}

Related

Flutter - SQFlite query of period between two dates does not return data

I'm performing a database query from a Flutter application in which I need to bring records in the period between two dates. However, the query does not return records even though there are records saved for this period.
The query below returns zero records:
final List<Map<String, dynamic>> records = await db.rawQuery(
'SELECT * FROM vehicles WHERE created BETWEEN 2022-07-17 AND 2022-08-16');
Attempting not to use the BETWEEN clause as below did not work either
final List<Map<String, dynamic>> records = await db.rawQuery(
'SELECT * FROM vehicles WHERE created >= 2022-07-17 AND created <= 2022-08-16');
I also emphasize that the "created" column of the "vehicles" table stores String dates in the following format: YYYY-MM-DD and that the console does not report any syntax errors, it just does not working
I guess the problem is that you haven't added quotes in date.
So it should look like this:
final List<Map<String, dynamic>> records = await db.rawQuery(
"SELECT * FROM vehicles WHERE created BETWEEN '2022-07-17' AND '2022-08-16'");
or like this:
final List<Map<String, dynamic>> records = await db.rawQuery(
"SELECT * FROM vehicles WHERE created >= '2022-07-17' AND created <= '2022-08-16'");

How to reset auto increment id in SQLite table in Dart

I need to reset the automatic incremental ID to 0. When I delete every record from the table, the data will be deleted, then adding new data onto the table, the numbering continues from where it was before. I tried
db.delete('table_name'); // works fine. but numbering continues.
....
db.execute('TRUNCATE TABLE table_name'); // shows exception
The exception I get is:
DatabaseException(near "TRUNCATE": syntax error (code 1 SQLITE_ERROR):
How to fix this ?
This will reset the sequence index for the table you specify
await db!.delete('table_name');
await db!.update('sqlite_sequence', {'seq':1}, where: 'name = ?', whereArgs: ['table_name']);
To query all tables in sqlite schema you can use:
Future<List<Object>> showTables() async {
List<Object> tableNames = [];
List<Map<String, Object?>> tables = await db!.rawQuery("SELECT * FROM sqlite_master WHERE type=?", ['table']);
for (Map<String, Object?> table in tables) {
tableNames.add(table['name']!);
}
return tableNames;
}

How to combine 2 or more Sqflite queries with logical operators?

Im currently trying to combine the results of 2 queries in flutter. These are the queries:
Future<List> filterExercises({
List<String> equipmentFilter,
List<String> muscleFilter,
int custom, //0 = false, 1 = true
int recent, //0 = false, 1 = true
String orderBy,
}) async {
Database db = await initDatabase();
final muscleRes = await db.query(
'exercises',
where: "targetMuscle IN (${('?' * (muscleFilter.length)).split('').join(', ')})",
whereArgs: muscleFilter,
);
final equipmentRes = await db.query(
'exercises',
where: "equipment IN (${('?' * (equipmentFilter.length)).split('').join(', ')})",
whereArgs: equipmentFilter,
);
return finalResult; //need to combine the results with a logical AND somehow
}
I know there's the option the use a rawQuery with logical OR / AND, but that doesn't work for my case.
It should be possible for the user to select different attributes and thus filter the list. Im looking for a way to pass arguments to this function and query my table accordingly to the passed arguments but I already fail when merging the first two queries.
How to add a logical AND to these two queries?
And furthermore: How to add even more attributes with a logical AND and order the final result?
I managed to find a way to the first question:
List<String> muscleFilter = ['Chest', 'Biceps'];
List<String> equipmentFilter = ['Machine', 'Cable'];
return db.rawQuery('''
select * from exercises
where targetMuscle in (${('?' * (muscleFilter.length)).split('').join(', ')})
and equipment in (${('?' * (equipmentFilter.length)).split('').join(', ')})
''',
muscleFilter + equipmentFilter
);

Check which PKs in List of PKs is present within SQFLITE database

For a list of PKs of length k:
listPK = [1,2,3...k]
I'm currently running a for loop, and querying the database k times to check whether the item is present within the database or not.
List<bool> isPresent(List listPK)async{
final db = await database;
List<bool> output = List.filled(listPK.length, false)
for (var i = 0; i<listPk.length; i++){
List<Map> result = await db.query('elements', where: "id = ?", whereArgs: listPk[i]);
if (result[0] != null) {output[i] = true}
}
}
Was wondering if there was a more efficient way to do this. I only want to know if the id is present within the database or not.
Use a WHERE ... IN to check against all the IDs in one call.
String listQuery = listPK.join(', '); // "1, 2, 3, ..., k"
String query = 'SELECT * FROM table_name WHERE id IN ($listQuery);`;
List<Map> result = await db.rawQuery(query);
It would be more efficient to query the database once and get all the id's in the 'elements' table. Once you have all the id's in the 'elements' table you can iterate through and find which id's are present and which are not.

Multiple arguments in sqllite in flutter

I would like to know how to pass multiple arguments to a raw query in sqllite.
My code is below
query() async {
// get a reference to the database
Database db = await DatabaseHelper.instance.database;
// raw query
List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=?', ['Peter']);
// print the results
result.forEach((row) => print(row));
}
In the above code i am passing one argument 'Peter' but what if I want to pass multiple arguments, for example:
List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=? and last_name=? and year=?', ['Peter'], ['Smith'],[2019]);
If I do the code above, I get error "Too many positional arguments: 2 expected, but 4 found." can someone show me how to pass multiple arguments to a query in sqllite flutter?
I'm assuming you're using sqflite.
You need to put all your arguments into one list and not multiple.
The code below should work like this:
List<Map> result = await db.rawQuery(
'SELECT * FROM my_table WHERE name=? and last_name=? and year=?',
['Peter', 'Smith', 2019]
);
For more examples how to use raw queries see their examples on their pub.dev page.
Or if you want to use the query function you can do it like this:
String strVal = 'str';
int intVal = 0;
String likeVal = 'str';
final List<Map<String, dynamic>> maps = await db.query('my_table',
where: "col1 LIKE ? and col2 = ? and col3 = ?",
whereArgs: ['$likeVal%', strVal, intVal],
orderBy: 'id',
limit: 10);