我可以连接到我的数据库,但是 psycopg2 找不到我的任何表。以下将在尝试获取我的用户时出错:
import psycopg2
try:
conn = psycopg2.connect("dbname='pdb' user='postgres' host='localhost' password='password'")
except:
print 'failed to connect'
cur = conn.cursor()
cur.execute(""" SELECT * from Users """)
rows = cur.fetchall()
for row in rows:
print row[0]
#Error:
psycopg2.ProgrammingError: relation "users" does not exist
LINE 1: SELECT * from Users
# This also fails
cur.execute("""SELECT * from pdb.Users """)
如果我这样做:
cur.execute(""" SELECT * from pg_database """)
# Outputs
template1
template0
postgres
pdb
在我的管理面板中,pdb 显示了一堆表,其中一个是 Users
,所以我不确定为什么 psycopg2 找不到它。
这是 pdb
的 psql 打印输出:
List of relations
Schema | Name | Type | Owner
--------+--------------------+-------+----------
public | Companies | table | postgres
public | Users | table | postgres
(2 rows)
最佳答案
您的表名 Users
和 Companies
均以大写字母开头。 PostgreSQL 会将所有标识符转换为小写(默认情况下),您可以从错误消息中看到:
psycopg2.ProgrammingError: relation "users" does not exist
users
全部小写。如果您希望严格遵循 SQL 标准(因为 PostgreSQL 是著名的),这是必需的。您可以通过两种方式解决此问题:
在你的数据库中解决它:
遵守通用约定并将您的表重命名为全部小写。
在你的代码中解决它:
引用你的标识符(在本例中是你的表名),这样 PostgreSQL 将保持它们不变:
cur.execute(""" SELECT * from "Users" """)
关于python - 连接后 psycopg2 找不到任何表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27434633/