简体   繁体   中英

Python remove the single quotes from the dictionary

I have following PostgreSQL query

data = {'token':"123",'kart_user':"tablename"}
select_stmt = "SELECT * FROM %(kart_user)s WHERE token = %(token)s"
self.cur.execute(select_stmt, data)
result = self.cur.fetchone() 

In the select query %(kart_user)s is represent in the form of single quotes
My question is how can i remove the quotes from the same query??.

The whole point of using SQL parameters is to prevent data being interpreted as SQL objects or syntax. You can't use SQL parameters to name tables; you can only use SQL parameters for data.

You'll have to interpolate table names separately. This does means you run a risk of opening up your code to SQL injections; I'd test the table name against a list of known tablenames if this is sourced from user input.

assert data['kart_user'] in known_tables
select_stmt = "SELECT * FROM {} WHERE token = %(token)s".format(data['kart_user'])
self.cur.execute(select_stmt, data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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