Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
yoohoo Avatar asked Oct 07 '19 20:10

yoohoo


2 Answers

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.

like image 153
Hannes Küttner Avatar answered Sep 28 '22 01:09

Hannes Küttner


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);
like image 38
live-love Avatar answered Sep 28 '22 03:09

live-love