趣味のアプリをつくる際にdb接続が必要になった。
自分のmacbookProの環境を汚したくなかったのでvagrantで仮想環境を作成してその上でデータベースをインストールすることにした。
vagrant設定
ubuntuのイメージがほしいのでvagrantの公式サイトで入手する。
サイトに記載のあるコマンドでVagrantfileを作成する。
vagrant init ubuntu/trusty64 vagrant up
Vagrantfileの作成が完了したら仮想環境に入れるか確認する。
vagrant ssh
仮想環境に入れたら一旦抜けて、テキストエディタでVagrantfileの下記コメントアウトを外してポートを開通させておく。
config.vm.network "forwarded_port", guest: 5432, host: 5432
vagrantを再起動させる。
vagrant reload
postgres設定
下記コマンドでpostgresSQLをインストールする。
sudo apt-get install postgresql
vagrantのpostgresqlをpgAdmin4で接続したいため下記設定をする。
1. pgAdmin4のインストール
- postgresql.confの変更
下記に変更
$ diff postgresql.conf postgresql.conf_bk 59c59 < listen_addresses = '*' # what IP address(es) to listen on; --- > #listen_addresses = 'localhost' # what IP address(es) to listen on;
- pg_hba.confの変更
下記に変更
$ sudo diff pg_hba.conf pg_hba.conf_bk 92c92 < host all all all trust --- > host all all 127.0.0.1/32 md5
- postgresqlを再起動する
linuxの場合下記コマンドで一度postgresqlを再起動する。
sudo service postgresql restart
- pgAdmin4でデータベースに接続する
長いので下記ブログを参照。
(途中出てくるusernameとpasswordは適当でもOK?)
- 各種テーブルとデータを作成
こちらも操作手順が長いので下記ブログを参照。
- 実際にDBを確認
実際にvagrantに入って作成したテーブルとデータをpostgresqlのCLIで確認する。
postgressqlにログインする。
sudo -u postgres psql
¥lでデータベースを確認する。
postgres=# \l 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 testdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
¥cでデータベースを切り替える。
postgres=# \c testdb You are now connected to database "testdb" as user "postgres". testdb=#
select文でデータを確認する。
testdb=# select * from menu; 1 | テスト弁当 | 400 | 400
データも入っていて日本語の文字化けないのでこれでデータベースOK!
mysqlの文字化けで苦労したのでこんなに簡単にデータを作成できるとは。
今後はpostgresqlを使おう。
今回は一旦ここまで。次回からpythonの導入と実際にアプリの開発を始める。