Parameterized queries with the Python Cassandra Module

点点圈 提交于 2019-12-08 13:08:55

问题


I've been experimenting with the CQL plugin for Python (http://code.google.com/a/apache-extras.org/p/cassandra-dbapi2/) which has support for parameterized queries. From their documentation:

import cql
connection = cql.connect(host, port, keyspace)
cursor = connection.cursor()
cursor.execute("CQL QUERY", dict(kw='Foo', kw2='Bar', etc...))

My question is whether its possible to parameterize and execute the same query multiple times in a loop, and what the methods look like to accomplish that. Sorry but documentation is scant so I'm searching about for an answer...


回答1:


Take a look at the code in tests for more examples

import cql
connection = cql.connect(host, port, keyspace)
cursor = connection.cursor()

query = "UPDATE StandardString1 SET :c1 = :v1, :c2 = :v2 WHERE KEY = :key"
cursor.execute(query, dict(c1="ca1", v1="va1", c2="col", v2="val", key="ka"))
cursor.execute(query, dict(c1="cb1", v1="vb1", c2="col", v2="val", key="kb"))
cursor.execute(query, dict(c1="cc1", v1="vc1", c2="col", v2="val", key="kc"))
cursor.execute(query, dict(c1="cd1", v1="vd1", c2="col", v2="val", key="kd"))

Or more specifically to your question about running it in a loop:

import cql
connection = cql.connect(host, port, keyspace)
cursor = connection.cursor()

query = "UPDATE StandardString1 SET :c1 = :v1, :c2 = :v2 WHERE KEY = :key"
values = [dict(c1="ca1", v1="va1", c2="col", v2="val", key="ka"),
          dict(c1="cb1", v1="vb1", c2="col", v2="val", key="kb"),
          dict(c1="cc1", v1="vc1", c2="col", v2="val", key="kc"),
          dict(c1="cd1", v1="vd1", c2="col", v2="val", key="kd")]

for value in values:
    cursor.execute(query, value)


来源:https://stackoverflow.com/questions/15683989/parameterized-queries-with-the-python-cassandra-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!