1

How can I pass dict and query parameters?

I can do such code.

prepared = session.prepare('select name from task where id = ?;')
bound = prepared.bind([1])
session.execute(bound)

How can I use dict as parameters and what will be query syntax?

This not works:

prepared = session.prepare('select name from task where id = %(id)s;')
bound = prepared.bind({"id": 1})
session.execute(bound)

Can you help with this basic code - it looks that it is possible but I do not know valid query syntax?

Chameleon
  • 9,722
  • 16
  • 65
  • 127

1 Answers1

4
query = """
        INSERT INTO table_name (
            field_1,
            field_2
        ) VALUES (?, ?)
"""
cql_session.prepare(query).bind({'field_1': 'foo', 'field_2': 'bar'})

this works for us.

Docs says that

bind(values)

Binds a sequence of values for the prepared statement parameters and returns this instance. Note that values must be:

  • a sequence, even if you are only binding one value, or
  • a dict that relates 1-to-1 between dict keys and columns
Community
  • 1
  • 1
Rafał Łużyński
  • 7,083
  • 5
  • 26
  • 38
  • It looks very strange for me ':field1' can be good syntax but '?'. Are you sure that is not random effect since dict is not ordered but order can fit by lucky? – Chameleon Aug 23 '17 at 17:03
  • I guess it parses query and takes columns names, then takes value from dict by this column name and replace '?' with it. Anyway this is what docs tells us - *a dict that relates 1-to-1 between dict keys and columns* – Rafał Łużyński Aug 23 '17 at 20:58
  • I will test it since look like awesome syntax. – Chameleon Aug 24 '17 at 11:23