我正在尝试使用 psycopg2 向 postgres 关系数据库发送查询。下面是代码。我不断收到“未定义的表”错误:
E psycopg2.errors.UndefinedTable:关系“人”不存在
E 第 4 行:加入人物 p ON u.person_id=p.id
我该如何解决这个问题?
from itertools import starmap
import psycopg2
from psycopg2 import sql
db_conn = psycopg2.connect(db parameters)
db_cursor = conn.cursor()
query_fields = (
'u.username',
'p.first_name',
'p.last_name',
'ec.employee_code',
'ec.status'
)
flds = sql.SQL(', ').join(starmap(sql.Identifier, map(lambda f: f.split('.'), query_fields)))
query_str = sql.SQL(
"""
SELECT {fields}
FROM user u
JOIN person p ON u.person_id=p.id
JOIN employee_contract ec ON ec.person_id=p.id
WHERE u.username LIKE '%word%'
""").format(fields=flds)
db_cursor.execute(query_str)
results = db_cursor.fetchall()
for i in results:
print(i)
db_conn.commit()
db_conn.close()
提前致谢。 阿奇
通过编辑查询字符串解决了这个问题,如下所示:
query_str = sql.SQL(
"""
SELECT {fields}
FROM "user" u
JOIN person p ON {id1} = {id2}
JOIN employee_contract ec ON {id3} = {id4}
WHERE u.username LIKE '%asangole%'
""").format(fields=flds01, id1=sql.Identifier('u','person_id'),
id2=sql.Identifier('p','id'), id3=sql.Identifier('ec','person_id'),
id4=sql.Identifier('p','id'))