简体   繁体   English

Python从字典中删除单引号

[英]Python remove the single quotes from the dictionary

I have following PostgreSQL query 我有以下PostgreSQL查询

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 在选择查询中, %(kart_user)s以单引号的形式表示
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. 使用SQL参数的整是,以防止数据被解释为SQL对象或语法。 You can't use SQL parameters to name tables; 您不能使用SQL参数来命名表; you can only use SQL parameters for data. 您只能将SQL参数用于数据。

You'll have to interpolate table names separately. 您必须单独插入表名。 This does means you run a risk of opening up your code to SQL injections; 这确实意味着您冒着将代码打开到SQL注入的风险; 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)

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

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