我可以连接到我的数据库,但是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找不到它。
这是来自psql的pdb
打印输出:
List of relations
Schema | Name | Type | Owner
--------+--------------------+-------+----------
public | Companies | table | postgres
public | Users | table | postgres
(2 rows)
答案 0 :(得分:8)
您的表格名称Users
和Companies
都以大写字母开头。 PostgreSQL会将所有标识符转换为小写(默认情况下),如错误消息所示:
psycopg2.ProgrammingError: relation "users" does not exist
其中users
以小写字母书写。如果您希望严格遵循SQL标准(因为PostgreSQL闻名),则需要这样做。您可以通过两种方式解决此问题:
在您的数据库中解决它:
遵守通用约定并将表格全部重命名为小写。
在您的代码中解决它:
引用您的标识符(在这种情况下是您的表名),以便PostgreSQL保持不变:
cur.execute(""" SELECT * from "Users" """)
答案 1 :(得分:0)
当您连接到错误的数据库时,通常也会发生此问题。就我而言,我连接到错误的数据库 下面是我使用psycopg2库进行连接的代码
import psycopg2
try:
src_conn = psycopg2.connect("dbname={} user={} host=localhost password={}".format(self.src_db, self.src_db, self.src_url ,self.src_pwd))
if src_conn:
src_curr = src_conn.cursor()
print("Cursor found",src_curr)
src_curr.execute("select * from product_template")
recs = src_curr.fetchall()
print(recs)
else:
print("Cursor not found")
except Exception as ex:
print(ex)