1

I have following query to retrieve data from 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..

Abdul Razak
  • 2,654
  • 2
  • 18
  • 24

1 Answers1

1

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. 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.

Hardik Patel
  • 483
  • 4
  • 10