在python中使用变量更新cassandra的查询

时间:2016-11-10 17:11:02

标签: python cassandra datastax

我正在尝试使用变量运行更新查询。我在datastax网站上使用casandra-driver作为指导。我使用以下脚本连接群集并更新表ct_table中的值。

from cassandra.cluster import Cluster
cluster = Cluster()
session = cluster.connect('ct_keyspace')
a=90
session.execute("update ct_table set value=%d where attribute='CT'",(int(a)))
result = session.execute("select * from ct_table where attribute='CT'")[0]
print result.attribute, result.value

我收到以下错误

Traceback (most recent call last):
  File "connection.py", line 7, in <module>
    session.execute("update ct_table set value=%d where attribute='CT'",(a))
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 1998, in execute
    return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 2035, in execute_async
    future = self._create_response_future(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state)
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 2095, in _create_response_future
    query_string = bind_params(query_string, parameters, self.encoder)
  File "/usr/local/lib/python2.7/dist-packages/cassandra/query.py", line 823, in bind_params
    return query % tuple(encoder.cql_encode_all_types(v) for v in params)
TypeError: 'int' object is not iterable

我的表格如下:

cqlsh:ct_keyspace> describe ct_table

CREATE TABLE ct_keyspace.ct_table (
    attribute text PRIMARY KEY,
    value int
) WITH bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';

value在表格中定义为int。我怀疑我正在格式化更新查询的字符串。

1 个答案:

答案 0 :(得分:2)

session.execute("update ct_table set value=%d where attribute='CT'",(int(a)))

应该是

session.execute("update ct_table set value=%s where attribute='CT'", (a,))

我们将绑定标记指定为%s并为参数列表传递元组。没有尾随逗号,它只是一个值。

另见:https://datastax.github.io/python-driver/getting_started.html#passing-parameters-to-cql-queries

  

请注意,您应该对所有类型的参数使用%s,而不仅仅是字符串