0
0

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 1 year has passed since last update.

PostgreSQLクライアントからの接続について

Posted at

はじめに

PostgreSQLと書いたり、PSQLと書いたり、言葉に揺らぎがあるかもしれませんがご容赦ください。
Almalinux8.6のコンテナで環境構築しています。

サーバーとクライアント

PostgreSQLに限った話ではないですが、
DBサーバーと、DBを利用するクライアントは別物になります。
この記事は、DBを利用するクライアント側での説明となります。

PostgreSQLクライアントの設定

dnf標準のリポジトリからはインストールできないため、リポジトリを追加する必要があります。
また、標準リポジトリを利用しないように設定してからインストールする必要があります。
以下のコマンドになります。

# dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
# dnf -qy module disable postgresql
# dnf -y install postgresql13

PSQLクライアントからPSQLサーバーのDBへ接続

  • PSQLのユーザー名:dbuser
  • 接続したいDB名:dbname
  • 接続先ホスト名もしくはIPアドレス:hostname
# psql -U dbuser -d dbname -h hostname

ユーザーを確認する

dbname=# \du
 dbuser    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

DB一覧を表示

¥lと打ちたいところですが、バックスラッシュ()+lです。
MACの場合、Optionキーを押しながら¥キーでバックスラッシュを打てます。

dbname=# \l
                              List of databases
   Name    | Owner  | Encoding |  Collate   |   Ctype    | Access privileges 
-----------+--------+----------+------------+------------+-------------------
 dbname    | dbuser | UTF8     | en_US.utf8 | en_US.utf8 | 
 postgres  | dbuser | UTF8     | en_US.utf8 | en_US.utf8 | 
 template0 | dbuser | UTF8     | en_US.utf8 | en_US.utf8 | =c/dbuser        +
           |        |          |            |            | dbuser=CTc/dbuser
 template1 | dbuser | UTF8     | en_US.utf8 | en_US.utf8 | =c/dbuser        +
           |        |          |            |            | dbuser=CTc/dbuser
(4 rows)

DBの外からでもpsql -U dbuser -d dbname -h hostname -lで調べられます。

DB作成&削除

testdbという名前のDBを作成

dbname=# CREATE DATABASE "testdb";
CREATE DATABASE

DBを削除

dbname=# DROP DATABASE "testdb";
DROP DATABASE

テーブル作成&削除

作成コマンド

dbname=# CREATE TABLE fruit(id integer, fruit varchar(10), price integer);
CREATE TABLE

削除コマンド

dbname=# DROP TABLE fruit;
DROP TABLE

テーブルにレコードを追加

文字を打つ際は、シングルクォーテーションで囲う。ダブルクォーテーションだと失敗するので注意。

dbname=# INSERT INTO fruit(id,fruit,price) VALUES (1,'meron',3000);
INSERT 0 1

全レコード追加する場合は、カラム名を省略可能

dbname=# INSERT INTO fruit VALUES (2,'apple',100);
INSERT 0 1

SQLでテーブル内のレコードを確認

dbname=# SELECT * FROM fruit;
  1 | meron |  3000

SQLコマンドは、書いていると長くなるのでここまでにします。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?