简体   繁体   English

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

[英]Python string substitution for dynamic column name and values

I have following query to retrieve data from PostgreSQL. 我有以下查询以从PostgreSQL检索数据。

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

Some case dictionary may contain multiple keys and values 某些情况下的字典可能包含多个键和值
Eg- 例如-

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

In this case how i can dynamically specify the column name and its values?? 在这种情况下,我如何动态指定列名及其值?

I have tried.. 我努力了..

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

But no luck. 但是没有运气。 Thank you for your response.. 感谢您的答复..

As per your tried statement, I assume you have three keys and three values so you want to execute SELECT statement for all three one by one. 根据您的try语句,我假设您有三个键和三个值,因此您要一一执行所有三个键的SELECT语句。 Below solution will help you. 以下解决方案将为您提供帮助。

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.

@ For and conditions @对于条件

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.

One liner solution for above answer, 一个以上答案的班轮解决方案,

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.

If your query is different then what I answered then reply on this. 如果您的查询不同,那么我回答了这个问题。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM