postgreSQLを起動させて基本的なデータベース操作をささっと。
※行頭がpsql外では$、**psql内では#**でコマンドを記述してある
データベースの新規作成/削除
DB作成
psql外で行う場合
$ createdb <DB name>
psql内で行う場合
# create database <DB name>;
DB削除
psql外で行う場合
$ dropdb <DB name>
psql内で行う場合
# drop database <DB name>;
DB一覧を表示
psql外で行う場合
$ psql -l
psql内で行う場合
$ \l
データベースに入る/出る/切り替え
DB入
様々な指定をして入ることが可能だが、少なくともこの2つだけは忘れないようにする。
# DB名のみを指定して入る
$ psql <DB name>
# DB名とユーザー名を指定して入る
$ psql -U <User name> <DB name>
DB出
MySQLにはexit;しかないがpostgreSQLには2つある。どちらでも動く。;は不要
# \q
# exit
DB切り替え
切り替えはpsql内で行う。以下のどちらでも動作する。;は不要
# \c <DB name>
# \connect <DB name>
挙動
DB操作の一通りの挙動を示す
sf213471118:postgres sf213471118$ psql -l /* 最初の状態 */
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+-------------+----------+---------+-------+-----------------------
postgres | sf213471118 | UTF8 | C | C |
template0 | sf213471118 | UTF8 | C | C | =c/ sf213471118 +
| | | | | sf213471118=CTc/ sf213471118
template1 | sf213471118 | UTF8 | C | C | =c/ sf213471118 +
| | | | | sf213471118=CTc/sf213471118
(3 rows)
sf213471118:postgres sf213471118$ createdb hogeDB /* hogeDB作成 */
sf213471118:postgres sf213471118$ psql -U aa291336 hogeDB /* hogeDB入 */
psql (11.4)
Type "help" for help.
hogeDB=# \connect postgres /* postgresに切替 */
You are now connected to database "postgres" as user "sf213471118".
postgres=# drop database "hogeDB"; /* hogeDB削除 */
DROP DATABASE
postgres=# \q /* postgres出 */
以上のように動く。
DB内の文字の扱いについて
上記の挙動におけるhogeDB削除の部分に関しては、""で括らないと
postgres=# drop database hogeDB;
2019-07-19 15:32:41.280 JST [57231] ERROR: database "hogedb" does not exist
2019-07-19 15:32:41.280 JST [57231] STATEMENT: drop database hogeDB;
ERROR: database "hogedb" does not exist
のようにエラーを吐く。このエラーは hogeDB が大文字を含むことから発生している。
データベースは二重引用符を使用して作成されているため、大文字/小文字は区別される。
そのため参照するときは二重引用符""を使用する必要がある。
このことから纏めると
- psql外(DB外)
-
dropdb hogeDB--> 通る -
dropdb "hogeDB"--> 通る
-
- psql内(DB内)
-
drop database hogeDB--> 通らない -
drop database "hogeDB"--> 通る
-
createdb/create databaseに関しては両方とも参照は必要ないため""で括る必要はない。