yoohoo
yoohoo

Reputation: 1217

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?

Upvotes: 14

Views: 11190

Answers (2)

live-love
live-love

Reputation: 52444

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);

Upvotes: 13

Hannes K&#252;ttner
Hannes K&#252;ttner

Reputation: 978

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.

Upvotes: 24

Related Questions