Lukasz
Lukasz

Reputation: 2317

inserting value of map to string

I took a look at the postgresql driver dokumentation. I found the following code there.

conn.query('select color from crayons where id = @id', {'id': 5})
  .toList()
    .then((result) { print(result); });

conn.execute('insert into crayons values (@id, @color)',
             {'id': 1, 'color': 'pink'})
    .then((_) { print('done.'); });

I wanted to test the inserting of the id into the string and put the following code into try.dart.org

// Go ahead and modify this example.

void main() {
var string = 'select color from crayons where id = @id', {'id': 5};
  print(string);
}

Unfortunately this gives me the following error Compilation failed: Expected identifier, but got '{'.. I also tried a few abbreviations but nothing helped.

So the question is. How do I properly insert the values of a map into a string?

Upvotes: 1

Views: 164

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657308

Your example code from the PostgreSQL driver means that the query() method expects two arguments, a string and a map.

Your 2nd example seems to try to do string interpolation. In Dart this would look like

var id = 5;
var string = 'select color from crayons where id = $id'; // or ${id}
  print(string);

Please don't try this for SQL. This opens a big hole for SQL injection attachs.

PostgresSQL does it's own string interpolation in a safe way.

Upvotes: 4

Related Questions