我试图在SQL中使用字符串格式。但是在传入变量时,这些变量是用引号插入的,并破坏了语法。
示例
这里,我试图将表名传递给函数。
def see_results(cur, table):
print("complete")
cur.execute(''' SELECT * from %s ''', (table,))
results = cur.fetchall()
print(results)
问题
如果我将"temp_yellow_pages"
作为参数传递,则结果查询是:''' SELECT * from "temp_yellow_pages" '''
。这个破了。
我想不出一种将任何东西分配给变量table
而不使用"
的方法,因为query = temp_yellow_pages
也会中断。
发布于 2022-01-10 12:29:33
字符串构建(易于SQL注入)
什么赫尔伍德
def selectFrom(table):
return 'SELECT * FROM ' + table
def see_results(cur, table):
print("complete")
cur.execute(selectFrom(table))
results = cur.fetchall()
print(results)
甚至直接使用f字符串cur.execute(f"SELECT * FROM {table}"
。
但是,如果传递的参数table
中有恶意输入,比如附加的DROP
或TRUNCATE
语句( statement ),怎么办?
查询构建(更安全)
使用https://pypi.org/project/psycopg/之类的具有SQL功能的库( safe或https://pypi.org/project/psycopg/),您可以使用应用输入验证的安全方法来构建SQL。
请参阅模块psycopg2.sql
中的示例,以便为给定的表参数组合SQL-语句。
from psycopg2 import sql
cur.execute(
sql.SQL("SELECT * FROM {} WHERE values IN (%s, %s)")
.format(sql.Identifier('my_table')),
[10, 20])
https://stackoverflow.com/questions/70658045
复制相似问题