컴퓨터 일반

[PostgreSQL] 설치 및 기초 명령어 정리

Folivora 2020. 3. 1. 07:53

설치하기 (Ubuntu 기준)

$ sudo apt install postgresql

 

데이터베이스 관리 콘솔에 들어가기

$ psql

 

psql: FATAL:  role "유저이름" does not exist 이라는 메시지가 뜰 것이다. 리눅스의 postgres 계정 권한으로 실행해야 한다.

$ sudo -u postgres -i
postgres@호스트이름:~$ psql

psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1))
Type "help" for help.

postgres=# 

 

데이터베이스 생성하기

postgres@호스트이름:~$ createdb 데이터베이스이름

데이터베이스의 Owner를 미리 지정할 수도 있다. 아래 데이터베이스 유저 생성하는 법 참조.

$ createdb -O 데이터베이스유저이름 데이터베이스이름

 

데이터베이스 목록보기

$ psql --list

                                      List of databases
     Name      |     Owner     | Encoding |   Collate   |    Ctype    |   Access privileges   
---------------+---------------+----------+-------------+-------------+-----------------------
 postgres      | postgres      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0     | postgres      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
               |               |          |             |             | postgres=CTc/postgres
 template1     | postgres      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
               |               |          |             |             | postgres=CTc/postgres
 test_db       | postgres      | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 

createdb test_db를 실행한 결과다. Owner가 postgres로 되어 있다.

 

혹은 psql 안이라면 \l 명령을 사용할 수 있다. 실행 결과는 동일.

postgres=# \l

 

데이터베이스 Owner 변경

postgres=# ALTER DATABASE 데이터베이스이름 OWNER TO 데이터베이스유저이름;
ALTER DATABASE 라는 메시지가 뜨면 변경 완료. \l (list) 명령어로 확인

 

(참고) psql에서 ; (semi-colon) 넣지 않고 엔터를 치면 쿼리 버퍼(query buffer)에 들어간다. \r 은 쿼리 버퍼를 리셋하는 명령어.

In psql, pressing enter without a semicolon continues the statement onto the next line, adding what you wrote to the query buffer rather than executing it. You will notice that the prompt changes from dbname=> to dbname-> to indicate that you're on a continuation line.

 

데이터베이스 삭제하기 (주의! 되돌릴 수 없음)

$ dropdb 데이터베이스이름

 

데이터베이스 유저 생성하기

$ createuser 데이터베이스유저이름

 

데이터베이스 유저 삭제하기

$ dropuser 데이터베이스유저이름

 

(참고) 어떤 한 데이터베이스가 유저를 참조하고 있으면 삭제되지 않는다.

 

데이터베이스 유저 목록보기

psql 안에서 \du 명령. display users의 약자인 듯.

postgres=# \du

                                     List of roles
   Role name   |                         Attributes                         | Member of 
---------------+------------------------------------------------------------+-----------
 postgres      | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 test_user     |                                                            | {}

 

데이터베이스 유저 암호 변경

postgres=# \password 데이터베이스유저이름;
Enter new password: <암호 입력>
Enter it again: <암호 입력>

 

파이썬 3용 PostgreSQL 바인딩 관련 설치

apt를 이용해서 설치하기
$ sudo apt install python3-psycopg2

 

pip3을 통해서 설치하기 (그러나 libpq-dev 패키지가 필요하다)
$ sudo apt install libpq-dev
$ sudo pip3 install psycopg2