Python과 Postgresql을 연결하고 DB에 있는 User 테이블 데이터를 조회하는 과정에서 문제가 발생했다.
cursor.execute('SELECT * FROM public.User')
rows = cursor.fetchall()
rows
구글링 해보니 postgresql은 mysql과 달리 {스키마명}.{테이블명}
으로 조회되어야한다.
따라서 위 코드를 실행했으나 아래와 같이 해당 릴레이션이 없다는 에러가 나왔다.
분명히 DB에는 Users 테이블이 있는데 왜 저런 에러가 나왔을까
1. Python 연결 여부
import psycopg2
connect = psycopg2.connect(
host = 'localhost',
dbname="postgres",
user="postgres",
password="{password}",
port={port}
)
print(connect)
# <connection object at 0x000002143E07D6A0; dsn: 'user=postgres password=xxx dbname=postgres host=localhost port=5432', closed: 0>
connection은 잘 된 것으로 보인다.
2. 스키마 목록 출력
cursor.execute("SELECT schema_name FROM information_schema.schemata;")
schema_list = cursor.fetchall()
print("스키마 목록:")
for schema in schema_list:
print(schema[0])
# 스키마 목록:
# public
# information_schema
# pg_catalog
# pg_toast
스키마 목록이 모두 정상적으로 출력되고 있다.
3. 스키마에 있는 모든 테이블 목록 조회
from psycopg2 import sql
for schema in schema_list:
query = sql.SQL("SELECT table_name FROM information_schema.tables WHERE table_schema = {};").format(sql.Literal(schema[0]))
cursor.execute(query)
table_list = cursor.fetchall()
print(f"{schema[0]} 스키마의 테이블 목록:")
for table in table_list:
print(table[0])
# public 스키마의 테이블 목록:
# User
# information_schema 스키마의 테이블 목록:
# collations
# information_schema_catalog_name
# applicable_roles
# domain_constraints
# administrable_role_authorizations
# collation_character_set_applicability
# attributes
# character_sets
# ...
public 스키마의 테이블 목록에 User가 출력되었다.
그럼 public 스키마 안에 User 테이블이 확실히 있다는 것인데 왜 릴레이션이 없다고 나올까
혹시 query문이 잘못되었는지 확인하기 위해 직접 DB에 접속해 하나의 데이터에 대해 SQL문을 생성해주는 도구를 활용해보았다.
위 사진과 같이 스키마.{테이블명}
이 아닌 스키마."{테이블명}"
으로 생성된 것을 확인할 수 있었다.
따라서 쿼리문이 잘못되었다는 것을 확인한 후, 테이블명을 큰따옴표로 감싸준 뒤 다시 실행해보았다.
cursor.execute('SELECT * FROM public."User"')
rows = cursor.fetchall()
rows
이제 데이터가 정상적으로 조회되는 것을 확인할 수 있다.