连接后psycopg2找不到任何表

use*_*398 5 python postgresql psycopg2

我可以连接到我的数据库,但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 """)
Run Code Online (Sandbox Code Playgroud)

如果我做:

cur.execute(""" SELECT * from pg_database """)

# Outputs
template1
template0
postgres
pdb
Run Code Online (Sandbox Code Playgroud)

在我的管理面板中,pdb显示了一堆表,其中一个是Users,所以我不确定为什么psycopg2找不到它.

这是psql的打印输出pdb:

               List of relations
 Schema |        Name        | Type  |  Owner   
--------+--------------------+-------+----------
 public | Companies          | table | postgres
 public | Users              | table | postgres
(2 rows)
Run Code Online (Sandbox Code Playgroud)

Tim*_*san 10

你的表名Users,Companies都以大写字母开头.PostgreSQL会将所有标识符转换为小写(默认情况下),如错误消息所示:

psycopg2.ProgrammingError: relation "users" does not exist
Run Code Online (Sandbox Code Playgroud)

在哪里users写小写.如果您希望严格遵循SQL标准(因为PostgreSQL闻名),则需要这样做.您可以通过两种方式解决此问题:

在您的数据库中解决它:

坚持一个共同的约定并将您的重命名为全小写.

在你的代码中解决它:

引用你的标识符(在这种情况下是你的表名),这样PostgreSQL会保持不变:

cur.execute(""" SELECT * from "Users" """)
Run Code Online (Sandbox Code Playgroud)