psycopg2 中的 Postgresql 语句未返回预期值
Postgresql statement in psycopg2 not returning expected values
我建立了一个 postgresql 数据库。我 运行 以下代码在 table 的 'state' 列中获取唯一值(这些是表示 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()
这个returns:
results
('state',)
如果我 运行 在 PGAdmin4 中进行相同的查询,我得到:
example_db=# SELECT DISTINCT state FROM example_table;
state
-------
06
(1 row)
我想使用 psycopg2 获取不同的值(即本例中的 06)。我需要更改什么?
示例:
from psycopg2 import sql
cursor.execute(sql.SQL('SELECT DISTINCT {} FROM example_table').format(sql.Identifier('state')))
问题是 state
是一个标识符(列名),您不能使用参数将其包含在查询中。您需要使用 psycopg2.sql 模块将标识符构建到查询中。
数据库对象的名称,例如 table 或列名,不能作为 SQL 字符串文字传递以进行转义。
见psycopg2.sqlmodule
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)
我建立了一个 postgresql 数据库。我 运行 以下代码在 table 的 'state' 列中获取唯一值(这些是表示 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()
这个returns:
results
('state',)
如果我 运行 在 PGAdmin4 中进行相同的查询,我得到:
example_db=# SELECT DISTINCT state FROM example_table;
state
-------
06
(1 row)
我想使用 psycopg2 获取不同的值(即本例中的 06)。我需要更改什么?
示例:
from psycopg2 import sql
cursor.execute(sql.SQL('SELECT DISTINCT {} FROM example_table').format(sql.Identifier('state')))
问题是 state
是一个标识符(列名),您不能使用参数将其包含在查询中。您需要使用 psycopg2.sql 模块将标识符构建到查询中。
数据库对象的名称,例如 table 或列名,不能作为 SQL 字符串文字传递以进行转义。 见psycopg2.sqlmodule
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)