1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PostgreSQL】インストール / 起動 / psql / psycopg2

Posted at

まとめ

  • PostgreSQL をインストールして、起動して、接続するまでの備忘録。
  • OS は Amazon Linux 2

インストール

yum で一発。

yum install postgresql-server

起動

起動してみます。

[root@ip-192-168-0-75 ~]# systemctl start postgresql.service
Job for postgresql.service failed because the control process exited with error code. See "systemctl status postgresql.service" and "journalctl -xe" for details.
[root@ip-192-168-0-75 ~]# 

失敗したので /var/log/messages を確認します。

[root@ip-192-168-0-75 ~]# cat /var/log/messages | grep postgresql
...(略)...
Nov 28 14:59:47 ip-192-168-0-75 postgresql-check-db-dir: "/var/lib/pgsql/data" is missing or empty.
Nov 28 14:59:47 ip-192-168-0-75 postgresql-check-db-dir: Use "postgresql-setup initdb" to initialize the database cluster.
...(略)...
[root@ip-192-168-0-75 ~]# 

Use "postgresql-setup initdb" と言われているので、そうします。

[root@ip-192-168-0-75 ~]# postgresql-setup initdb
Initializing database ... mkdir: cannot create directory ‘/var/lib/pgsql/data/pg_log’: File exists
failed, see /var/lib/pgsql/initdb.log

[root@ip-192-168-0-75 ~]# 

これも失敗します。 see /var/lib/pgsql/initdb.log だそうです。ふむ。

[root@ip-192-168-0-75 ~]# tail /var/lib/pgsql/initdb.log
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

initdb: directory "/var/lib/pgsql/data" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/var/lib/pgsql/data" or run initdb
with an argument other than "/var/lib/pgsql/data".
[root@ip-192-168-0-75 ~]# 

指示された通りに /var/lib/pgsql/data を消します。

[root@ip-192-168-0-75 ~]# rm -rf /var/lib/pgsql/data
[root@ip-192-168-0-75 ~]# 
[root@ip-192-168-0-75 ~]# postgresql-setup initdb
Initializing database ... OK

[root@ip-192-168-0-75 ~]# 
[root@ip-192-168-0-75 ~]# systemctl start postgresql.service
[root@ip-192-168-0-75 ~]# 

起動できました。

psql による接続

psql コマンドで接続を試みます。

[root@ip-192-168-0-75 data]# psql -d postgres -U postgres
psql: FATAL:  Ident authentication failed for user "postgres"
[root@ip-192-168-0-75 data]# 

が、失敗します。

PostgreSQL インストール時に追加される postgres ユーザにパスワードを設定した上で、このユーザで接続ができるようです。

[root@ip-192-168-0-75 ~]# su - postgres
Last login: Wed Nov 28 15:37:43 UTC 2018 on pts/0
-bash-4.2$ psql -d postgres -U postgres
psql (9.2.24)
Type "help" for help.

postgres=# ALTER USER postgres with encrypted password 'postgres';
ALTER ROLE
postgres=# \q
-bash-4.2$ logout
[root@ip-192-168-0-75 ~]# 

ここでパスワードを設定した上で、下の設定をいじる。

[root@ip-192-168-0-75 ~]# vi /var/lib/pgsql/data/pg_hba.conf 

修正前

...(略)...
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             postgres                                md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
...(略)...

修正後

...(略)...
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
...(略)...

パスワード認証を有効にして、一般ユーザからの接続も可能になります。

[ec2-user@ip-192-168-0-75 ~]$ psql -d postgres -U postgres
ユーザ postgres のパスワード: 
psql (9.2.24)
"help" でヘルプを表示します.

postgres=# 

ついでに DB を作成します。

postgres=# create database hoge_db;
CREATE DATABASE
postgres=# \d
リレーションがありません。
postgres=# \dt
リレーションがありません。
postgres=# \l
                                         データベース一覧
   名前    |  所有者  | エンコーディング |  照合順序   | Ctype(変換演算子) |      アクセス権       
-----------+----------+------------------+-------------+-------------------+-----------------------
 hoge_db   | postgres | UTF8             | en_US.UTF-8 | en_US.UTF-8       | 
 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
(4 行)

postgres=# 

psql から作った DB に接続できました。

[ec2-user@ip-192-168-0-75 ~]$ psql -U postgres -d hoge_db
ユーザ postgres のパスワード: 
psql (9.2.24)
"help" でヘルプを表示します.

hoge_db=# CREATE TABLE hoge_table (
hoge_db(#     fuga1 varchar(80),
hoge_db(#     fuga2 int
hoge_db(# );
CREATE TABLE
hoge_db=# INSERT INTO hoge_table VALUES ('hoge', 999);
INSERT 0 1
hoge_db=# 

ついでにテーブルを作ります。

Python からの接続

こいつらを入れます。

easy_install pip
pip install psycopg2
pip install psycopg2-binary

psycopg2 で接続できました。

[ec2-user@ip-192-168-0-75 ~]$ python
Python 2.7.14 (default, Jul 26 2018, 19:59:38) 
[GCC 7.3.1 20180303 (Red Hat 7.3.1-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> conn = psycopg2.connect(dbname="hoge_db", user="postgres", password="postgres", host="127.0.0.1", port="5432")
>>> cur = conn.cursor()
>>> cur.execute("select * from hoge_table;")
>>> cur.fetchone()
('hoge', 999)
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?