1

我想使用python driver执行多个 cql 语句(2 个或更多)。

我尝试了这样简单的代码,但如果查询包含多个语句,则会导致错误。我不想拆分语句或格式化它(单个语句)。我只想执行整个 CQL。

如何使用 Cassandra 的 python 驱动程序来做到这一点 - 有可能吗?

我使用;as 语句拆分。

from cassandra.cluster import Cluster


def main():
    cluster = Cluster(contact_points=['cassandra-1.', 'cassandra-2.', 'cassandra-3.', 'cassandra-4.'])
    session = cluster.connect()
    session.execute('drop keyspace if exists test')
    session.execute('''
        create keyspace test
        with durable_writes = true
        and replication = {
            'class' : 'SimpleStrategy',
            'replication_factor' : 3
        };    
    ''')
    session.set_keyspace('test')

    # two statements or more and there is error
    # how to execute all in one call?
    query = '''\
    create table x1 (
        name text,
        
        primary key ((name))
    );

    create table x2 (
        name text,
        
        primary key ((name))
    );
    '''

    result_set = session.execute(query)
    print(result_set)


if __name__ == '__main__':
    main()

它会产生这样的错误:

Traceback (most recent call last):
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandbox\cassandra_scheme\04_execute_multiple_statements.py", line 39, in <module>
    main()
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandbox\cassandra_scheme\04_execute_multiple_statements.py", line 34, in main
    result_set = session.execute(query)
  File "cassandra\cluster.py", line 2618, in cassandra.cluster.Session.execute
  File "cassandra\cluster.py", line 4894, in cassandra.cluster.ResponseFuture.result
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 7:4 mismatched input 'create' expecting EOF (... ((name))    );    [create]...)">
4

1 回答 1

1

每个语句应该是分开的。只需;使用 Python 代码拆分文本,然后分别执行它们。此外,请考虑到像您这样的编程模式修改具有潜在危险 - 您可能会遇到所谓的模式分歧,需要通过滚动重启集群来修复它。

于 2021-05-17T17:43:20.270 回答