【问题标题】:Update query for cassandra using variable in python使用python中的变量更新对cassandra的查询
【发布时间】:2017-03-24 19:43:25
【问题描述】:

我正在尝试使用变量运行更新查询。我正在使用 casandra-driver,按照 datastax 网站的指导。我正在使用以下脚本连接集群并更新表 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 。我怀疑我错误地格式化了更新查询的字符串。

【问题讨论】:

    标签: python cassandra datastax


    【解决方案1】:
    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,而不仅仅是字符串

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 2017-10-17
      • 2019-01-09
      • 2014-10-21
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      相关资源
      最近更新 更多