【问题标题】:Postgresql statement in psycopg2 not returning expected valuespsycopg2 中的 Postgresql 语句未返回预期值
【发布时间】:2021-12-28 19:54:28
【问题描述】:

我已经建立了一个 postgresql 数据库。我运行以下代码来获取表的“状态”列中的唯一值(这些是代表 FIPS 数字的字符串):

import psycopg2 as ps
con = ps.connect("dbname=example_db user=user password=password")
cursor = con.cursor()
cursor.execute('SELECT DISTINCT(%s) FROM example_table', ('state',))
results = cursor.fetchall()

这会返回:

results
('state',)

如果我在 PGAdmin4 中运行相同的查询,我会得到:

example_db=# SELECT DISTINCT state FROM example_table;

state
-------
06
(1 row)

我想使用 psycopg2 获取不同的值(在本例中为 06)。我需要改变什么?

【问题讨论】:

    标签: postgresql psycopg2


    【解决方案1】:

    例子:

    from psycopg2 import sql
    cursor.execute(sql.SQL('SELECT DISTINCT {} FROM example_table').format(sql.Identifier('state')))
    
    

    问题是state 是一个标识符(列名),您不能使用参数将其包含在查询中。您需要使用psycopg2.sql 模块将标识符构建到查询中。

    【讨论】:

    • 谢谢。我不知道我不能使用参数作为标识符。但是,我玩弄了它,如果我给表名加上别名,我​​就可以了,也就是说,这可行: cursor.execute('SELECT DISTINCT a.state FROM example_table a');不知道为什么会允许这样做?
    • 您显示的内容不使用参数,所以是的,它可以工作,以及cursor.execute('SELECT DISTINCT state FROM example_table')
    • 哦。呃。你说得对。我以为我试过了(即 cursor.execute('SELECT DISTINCT state FROM example_table') 并没有奏效,但再次尝试并成功了。感谢您的帮助!
    【解决方案2】:

    数据库对象的名称,例如表名或列名,不能作为 SQL 字符串文字传递以进行转义。 请参阅 psycopg2.sql module

    import psycopg2 as ps
    con = ps.connect("dbname=example_db user=user password=password")
    cursor = con.cursor()
    query = ps.sql.SQL('SELECT DISTINCT {column_name} FROM example_table').format(column_name=sql.Identifier('state'))
    cursor.execute(query)
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      相关资源
      最近更新 更多