psycopg2 cannot find any tables after connection

半世苍凉 提交于 2019-12-07 07:41:48

问题


I can connect to my database, but psycopg2 fails to find any of my tables. The following will error trying to get my users:

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 """)

If I do:

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

# Outputs
template1
template0
postgres
pdb

In my admin panel, pdb shows a bunch of tables, one of them being Users, so I'm not sure why psycopg2 can't find it.

Here's a printout from psql for pdb:

               List of relations
 Schema |        Name        | Type  |  Owner   
--------+--------------------+-------+----------
 public | Companies          | table | postgres
 public | Users              | table | postgres
(2 rows)

回答1:


Your table names Users and Companies both start with a capitalized letter. PostgreSQL will convert all identifiers to lower case (by default), as you can see from the error message:

psycopg2.ProgrammingError: relation "users" does not exist

Where users is written in all lower case. This is needed if you wish to strictly follow the SQL standard (as PostgreSQL is renowned for). You can solve this in two ways:

Solve it in your database:

Adhere to a common convention and rename your tables to be all lowercase.

Solve it in your code:

Quote your identifiers (your table name in this case) so PostgreSQL will leave them untouched:

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



回答2:


This issue also usually happens when you are connected to wrong database. In my case i was connected to wrong database Below is my code to connect using psycopg2 library

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)


来源:https://stackoverflow.com/questions/27434633/psycopg2-cannot-find-any-tables-after-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!