1 回答
TA贡献1789条经验 获得超8个赞
请参数化您的查询以避免 SQL 注入攻击。
if end_at and start_at:
currency = cursor.execute("""SELECT rates,date,ticker
FROM currency
WHERE ticker = %s
AND date BETWEEN SYMMETRIC %s AND %s """, (base, start_at, end_at, ))
print(cursor.query) # <--- This should log the complete query sent to the db server
要诊断手头的问题,请执行类似这样的操作以查看您发送的内容,但在将所有调用更改为参数化形式之前不要让您的应用程序生效。execute()
if end_at and start_at:
query = f"""SELECT rates,date,ticker
FROM currency
WHERE ticker = '{base}'
AND date BETWEEN SYMMETRIC '{start_at}' AND '{end_at}' """
print(query)
currency = cursor.execute(query)
在修复您的查询以使用参数后,要查看查询中发送到服务器的内容,请使用 作为LoggingConnection您现有的替代品psycopg2.Connection,如从我如何使用 Psycopg2 的 LoggingConnection 中提取的?.
import logging
import psycopg2
from psycopg2.extras import LoggingConnection
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
conn=psycopg2.connect(connection_factory=LoggingConnection, database='some_database')
conn.initialize(logger)
c = conn.cursor()
c.execute("select count(*) from some_table where id > %s", (1000, ))
使用我的基本配置,日志记录进入控制台:
DEBUG:__main__:b'select count(*) from some_table where id > 1000'
添加回答
举报