我有以下查询从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)
但没有运气。谢谢你的回复..
答案 0 :(得分:1)
根据您尝试过的声明,我假设您有三个键和三个值,因此您希望逐个执行所有三个的SELECT语句。以下解决方案将为您提供帮助。
docker exec --it <running_container> bash
@对于和条件
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.
如果您的查询不同,那么我的答案就会回复。感谢。