如何将dict绑定为preparedquery参数?

2024-10-03 15:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将一个dict绑定到一个准备好的语句的参数上,但是我似乎搞不懂语法。让我困惑的是,如果我在没有准备好的语句的情况下使用positional parameters它是有效的。在

看看这个例子:

from cassandra.cluster import Cluster


def works():
    id = '1'
    mydict = {'count': 1, 'value': 3}

    updateStmt = "insert into test.prep_test (id, mydict) values (%s, %s);"

    session.execute(updateStmt, (id, mydict))


def doesntwork():
    id = '2'
    mydict = {'count': 1, 'value': 3}

    updateStmt = "insert into test.prep_test (id, mydict) values (?, ?);"
    prep = session.prepare(updateStmt)

    session.execute(prep, [id, mydict])


if __name__ == "__main__":
    cluster = Cluster(['127.0.0.1'])
    session = cluster.connect('test')

    session.execute(
        'create table if not exists test.prep_test (  id ascii, mydict MAP<ascii,decimal>, PRIMARY KEY (id));')

    works()
    doesntwork()

    session.shutdown()
    cluster.shutdown()

works()方法可以很好地插入数据。但是,doesntwork()方法失败,错误如下:

^{pr2}$

Tags: testidexecutevaluesessiondefcount语句
1条回答
网友
1楼 · 发布于 2024-10-03 15:25:26

当您在works()的情况下运行它时,幕后的驱动程序使用字符串替换来生成以下查询,并将其提交给C*

'''insert into test.prep_test1 (id, mydict) values ('1', {'count': 1, 'value': 3});'''

这基本上是一个愚蠢的字符串替换。在

在第二种情况下,多个消息在服务器和客户端之间传递。首先准备一份声明。已准备好与服务器共享的关于此上下文的语句。这里的验证将更加严格,因为与查询相关联的上下文对驱动程序和服务器都是已知的。在

您可以通过在查询中使用适当的类型来解决这个问题。在本例中是将mydict绑定到上面建议的十进制值。在

^{pr2}$

或者,可以在表中使用int类型,如下所示。在

 'create table if not exists test.prep_test (  id ascii, mydict MAP<ascii,int>, PRIMARY KEY (id));')

你可能会争辩说驱动程序应该能够从int或float类型映射到decimal,但目前还不是这样工作的。在

相关问题 更多 >