如何解决正确使用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')])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。