Get Multiple Rows on SQLite in Flutter

830

If you wan select records where id in list of ids you should use query like

SELECT * FROM urun WHERE urunID IN (1, 2, 3);

You have two options.

  1. Provide same number of placeholders as list length
final placeholders = List.generate(5,(_) => "?").join(",");
var result = await db.query("$_prodTable", where: '$_columnProdID IN ($placeholders)', whereArgs: IDs);
  1. Since ids is integers just
var result = await db.query("$_prodTable", where: '$_columnProdID IN (${IDs.join(",")})');
Share:
830
Seyit Ahmet Gökçe
Author by

Seyit Ahmet Gökçe

Updated on December 11, 2022

Comments

  • Seyit Ahmet Gökçe
    Seyit Ahmet Gökçe over 1 year

    I keep only the "productID" information of the products added to the favorites in the "favorite" table in the database. I had no problem adding this information to the table. (product table and favorite table are separate.) But when I wanted to list all favorite products in the table, I found the codes that allowed me to query one by one. What I need is a function that can give the List<int> productIDs as parameter and return favorite products as List<Map<String, dynamic>>> . I looked almost everywhere but could not find it. The function I use to fetch favorite product IDs stored in the favorite table:

    Future<List<Map<String, dynamic>>> favProds() async{
        List<int> IDs = new List<int>();
        var db = await _getDatabase();
        var result = await db.query(_favTable, orderBy: '$_columnProdID DESC');
        for(Map incomingMap in result){
          IDs.add(incomingMap['prodID']);
        }
        return _getFavProdsWithIDList(IDs);
      }
    

    This is my function that takes the ID List as a parameter and returns a list containing favorite products as maps:

    Future<List<Map<String, dynamic>>> _getFavProdsWithIDList(List<int> IDs) async{
        var db = await _getDatabase();
        var result = await db.query("$_prodTable", where: '$_columnProdID = ?', whereArgs: IDs);
        return result;
      }
    

    Here is the error I get when I use them:

    Unhandled Exception: DatabaseException(Cannot bind argument at index 8 because the index is out of range.  The statement has 1 parameters.) sql 'SELECT * FROM urun WHERE urunID = ?' args [230, 180, 179, 20, 19, 18, 17, 2]}
    

    From this error, we see that adding products to the favorite table is successful.