正确使用Psycopg2 SQL模块

问题描述

由于语法错误(Maurice Meyer使我意识到)而编辑了问题

我需要保护应用程序免遭sql注入,因此请使用 Psycopg2 中的 sql 模块。这将生成一个有效的查询

conn = get_db()
cur = conn.cursor()
with open(fp,'r') as f:
    query = sql.sql("copY parts ({fields}) FROM STDIN WITH (FORMAT CSV,DELIMITER ';',ENCODING UTF8)").format(
        fields = sql.sql(',').join(sql.Identifier(col) for col in cols))
    cur.copy_expert(query,f)

但是我想知道这是否是正确的解决方案。由于生成查询是:

print(query.as_string(conn))
>>> copY parts ("asin","name","t_id","supp_pid","acq_price","deposit","ean","m_pid") FROM STDIN WITH (FORMAT CSV,ENCODING UTF8)

但是根据Postgresql docs,标识符应不加引号。 为什么它仍然可以工作?

解决方法

您有错字:

sql.SQL("xxx".format(...))

代替:

sql.SQL("xxx").format(...)
             ^ this (

如此:

query = sql.SQL("COPY parts ({fields}) FROM STDIN WITH (FORMAT CSV,DELIMITER ';',ENCODING UTF8)").format(
        fields = sql.SQL(',').join(sql.Identifier(col) for col in cols))
,

支架未正确合上。您在字符串上而不是在SQL对象上使用format

with open(fp,'r') as f:
    _sql = "COPY parts ({}) FROM STDIN WITH (FORMAT CSV,ENCODING UTF8)"
    query = sql.SQL(_sql).format(
        sql.SQL(',').join(sql.Identifier(col) for col in cols)
    )
    print(query.as_string(conn))
    cur.copy_expert(query,f)

输出:

COPY parts ("firstname","lastname") FROM STDIN WITH (FORMAT CSV,ENCODING UTF8)
Traceback (most recent call last):
  File "pg2.py",line 14,in <module>
    cur.copy_expert(query,f)
psycopg2.errors.UndefinedTable: relation "parts" does not exist

注意,关于引用的标识符:

想象一下,您有一个包含空格的列名,然后需要引用它们才能使用它们。因此,允许使用引号,对于postgres控制台也是如此。

>>> cur.execute("""select firstname,"desc ription" from users2 where lastname = 'bar'""")
>>> print(cur.fetchone())
RealDictRow([('firstname','fo'),('desc ription','baz')])