Dart mysql insert placeholders in map

182

maybe its a little to late, but for others finding this post. You can do it in this way, not perfect, but little more flexible:

final sql = '''
  INSERT INTO jobs 
    (${job.keys.toList().join(',')}) 
  VALUES 
    (${List.filled(job.keys.length, '?').join(',')})   
''';
await connection.query(sql, job.values.toList());
Share:
182
Petr Klein
Author by

Petr Klein

Updated on December 09, 2022

Comments

  • Petr Klein
    Petr Klein over 1 year

    1) Is there some chance to insert huge placeholder via Map?

    Example:

    Map<String, dynamic> job = {
        'status': 'test',
        'id_sitemap': 2500,
        'id_job': 12,
        'contact_uuid': 'nejakeuuid',
        'id_source': 250,
         ...
         more 90 cols
      };
    
      await connection.query('INSERT INTO jobs', job);
    

    2) How can I use mysql transaction? I'm using package mysql1 for Dart.

    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      "insert huge placeholder" what does that mean?
    • Petr Klein
      Petr Klein about 5 years
      thats mean I have table with 95 columns and I dont want write VALUES(?,?,?,?,?,?,?,?,?,?,?,......) and use strict positions of placeholders. I want use Map where the key is column name and value is column value. For better reading code.
    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      I see, but don't know.
  • Petr Klein
    Petr Klein almost 4 years
    Cool solution 👍