gpt4 book ai didi

动态列名称和值的 Python 字符串替换

转载 作者:搜寻专家 更新时间:2023-10-30 23:41:43 25 4
gpt4 key购买 nike

我有以下查询从 PostgreSQL 检索数据。

select_stmt = "SELECT * FROM kart_user WHERE token = %(token)s"
cursor.execute(select_stmt, { 'token': 2 })

某些案例字典可能包含多个键和值
例如-

{ 'token': 10,'custid':100,cycle:"yes" }

在这种情况下,我如何动态指定列名及其值??

我试过了..

select_stmt = "SELECT * FROM kart_user WHERE dist.keys() = %(dist.keys())s"
cursor.execute(select_stmt, dist)

但运气不好。感谢您的回复..

最佳答案

根据您尝试过的语句,我假设您有三个键和三个值,因此您想对所有三个键一一执行 SELECT 语句。以下解决方案将为您提供帮助。

d = { 'token': 10,'custid':100,cycle:"yes" }
select_stmt = "SELECT * FROM kart_user WHERE {key} = '{value}'"
allowed_col = ['token', 'custid'] # Predefined column names to allow from coming dictionary.
for key, value in d.iteritems():
if key in allowed_col:
select_stmt = select_stmt.format(key=key, value=value)
cursor.execute(select_stmt, dist)
# Further fetching code you can execute. Here you will get select statement for particular key and value.

@对于条件

d = { 'token': 10,'custid':100,'cycle':"yes" }
select_stmt = "SELECT * FROM kart_user WHERE"
allowed_col = ['token', 'custid'] # Predefined column names to allow from coming dictionary.
for key, value in d.iteritems():
if key in allowed_col:
condition = "{key} = '{value}'".format(key=key, value=value)
select_stmt = select_stmt + " and " + condition
cursor.execute(select_stmt, dist)
# Further fetching code you can execute. Here you will get select statement for particular key and value.

上述答案的一个线性解决方案,

d = { 'token': 10,'custid':100,'cycle':"yes" }
condition = ' and '.join([key+'="'+str(value)+'"' for key,value in d.iteritems() if key in allowed_col])
select_stmt = "SELECT * FROM kart_user WHERE"
select_stmt = " ".join([select_stmt, condition])
cursor.execute(select_stmt, dist)
# Further fetching code you can execute. Here you will get select statement for particular key and value.

如果您的查询与我回答的不同,请回复此问题。谢谢。

关于动态列名称和值的 Python 字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com