PostgreSQLでの「\c」コマンドによる接続先データベースの変更方法
psqlであるデータベースに接続した後、別のデータベースへの接続に切り替えたい場合がある。
現在のデータベースへの接続を「\q」コマンドで切断後、、再度psqlで別のデータベースに接続する、といった方法もあるが、psqlでの切断、接続やり直し、といった流れが少しだけ面倒かもしれない。
少しでも手間を省くには、「\c」コマンドで接続先データベースを変更すればよい。
\c データベース名 ユーザ名
と入力し、[Enter]キーを押すことで、接続先データベースとユーザ名を変更できる。
ユーザ名の指定が不要である場合は、ユーザ名を指定せず、
\c データベース名
と入力してもよい。
《備考》PostgreSQL8.1のヘルプに記載されている情報
  \c[onnect] [DBNAME|- [USER]]
                 connect to new database (currently "nobuneko_datanase")
※このヘルプは、使用方法だけでなく、「currently "データベース名"」の部分で、現在の接続先データベース名まで確認できるので分かりやすい。
《例》Linux(CentOS 5)+PostgreSQL 8.1で接続先データベースを変更する方法
[root@nobuneko ~]# psql -U postgres nobuneko_database
Welcome to psql 8.1.23, the PostgreSQL interactive terminal.
Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit
nobuneko_database=# \l
                List of databases
           Name            |  Owner   | Encoding 
---------------------------+----------+----------
 cat_database              | postgres | EUC_JP
 neko_database             | postgres | EUC_JP
 nobuneko_database         | postgres | EUC_JP
 postgres                  | postgres | UTF8
 template0                 | postgres | UTF8
 template1                 | postgres | UTF8
(6 rows)
「\c データベース名」でデータベースの接続先を他のデータベースに変更する例
《存在するデータベースを指定した場合》
nobuneko_database=# \c neko_database ※存在するデータベース「neko_database」を指定
You are now connected to database "neko_database". ※「データベース『neko_database』に接続されている」、とメッセージが出る。
《存在しないデータベースを指定した場合》
nobuneko_database=# \c test_database ※存在しないデータベース「test_database」を指定
FATAL:  database "test_database" does not exist ※データベース「test_database」は存在しないと警告が出る
Previous connection kept ※「これまでの接続が維持される」と警告が出る
「\c データベース名 ユーザ名」でデータベースの接続先を他のデータベースに変更する例
《存在するユーザを指定した場合》
neko_database=# \c cat_database postgres ※存在するユーザ「postgres」を指定
You are now connected to database "cat_database" as user "postgres". ※「データベース『cat_database』に、『postgres』ユーザとして接続されている」、とメッセージが出る。
《存在しないユーザを指定した場合》
neko_database=# \c cat_database testuser ※存在しないユーザ「testuser」を指定
FATAL:  role "testuser" does not exist ※ユーザ「testuser」は存在しないと警告が出る
Previous connection kept ※「これまでの接続が維持される」と警告が出る