pg8000 Can't Parameterize Queries

℡╲_俬逩灬. 提交于 2020-01-06 08:38:30

问题


I've been trying to use pg8000 to interact with my SQL server, but for some reason, it won't accept params properly. It does seem to recognize the paramstyle, and then knows to change those to the PostgreSQL params, but it never seems to pass the params through. I looked at the documentation example here (link) for examples, and they didn't work. Here are some examples:

query = """
        SELECT *
        FROM schema.table_name
        """
conn = pg8000.connect(**credential_dict)
cursor = conn.cursor()
cursor.execute(query)

This example works. The next two do not:

query = """
        SELECT *
        FROM %s
        """
conn = pg8000.connect(**credential_dict)
cursor = conn.cursor()
cursor.execute(query, 'schema.table_name')

query = """
        SELECT *
        FROM %s
        """
conn = pg8000.connect(**credential_dict)
cursor = conn.cursor()
cursor.execute(query, ('schema.table_name',))

These queries fail, but the error I get says the error is at the $1 which pg8000 converts the %s to.

What am I doing wrong?


回答1:


Try explicitly naming your parameter and passing as a dict:

param_dict = dict(table_name = 'schema.table_name')
query = """SELECT * FROM %(table_name)s"""
# cursor setup code...
cursor.execute(query, param_dict)


来源:https://stackoverflow.com/questions/52524736/pg8000-cant-parameterize-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!