$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.10
DISTRIB_CODENAME=quantal
DISTRIB_DESCRIPTION="Ubuntu 12.10"
以下のサイトを参考にした
http://www.kkaneko.com/rinkou/postgresinstall/postgreslinux.html
$ sudo apt-get install postgresql
$ sudo apt-get install postgresql-client-common
$ sudo apt-get install postgresql-common
$ sudo apt-get install postgresql-contrib
$ sudo apt-get install postgresql-9.1-postgis
$ sudo apt-get install pgadmin3
pgAdminの使い方は公式サイトで確認出来る(http://www.pgadmin.org/)
$ sudo apt-get install postgis
$ sudo service postgresql start
データベースディレクトリは/var/lib/postgresql/dataを利用するように設定した。postgresユーザに権限を付与。
$ sudo mkdir /var/lib/postgresql/data
$ sudo chown -R postgres:****** /var/lib/postgresql/data
データベースディレクトリにデータベースファイルを作成する。
$ /usr/lib/postgresql/9.1/bin/initdb --encoding='UTF-8' -D /var/lib/postgresql/data
接続に使用するユーザ(-U)、エンコーディング(-E)、データベース論理名を指定してデータベースを作成する。
$ createdb -U postgres -E UTF8 testdb
以下のコマンドでデータベースの一覧を表示出来る。
$ psql -U postgres -l
以下の様な感じで表示される。
$ psql -U postgres -l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
mydb | 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
testdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
(5 rows)
データベースにログイン
$ psql -U postgres -d testdb
テーブル作成のサンプル
CREATE TABLE order_records (
id INTEGER PRIMARY KEY NOT NULL,
year INTEGER NOT NULL CHECK ( year > 2008 ),
month INTEGER NOT NULL CHECK ( month >= 1 AND month <= 12 ),
day INTEGER NOT NULL CHECK ( day >= 1 AND day <= 31 ),
customer_name TEXT NOT NULL,
product_name TEXT NOT NULL,
unit_price REAL NOT NULL CHECK ( unit_price > 0 ),
qty INTEGER NOT NULL DEFAULT 1 CHECK ( qty > 0 ),
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP,
CHECK ( ( unit_price * qty ) < 200000 ) );
データ作成(INSERT)のサンプル
BEGIN TRANSACTION;
INSERT INTO order_records VALUES( 1, 2009, 10, 26, 'kaneko', 'orange A', 1.2, 10, current_timestamp, NULL );
INSERT INTO order_records (id, year, month, day, customer_name, product_name, unit_price, qty, created_at) VALUES( 2, 2009, 10, 26, 'miyamoto', 'Apple M', 2.5, 2, current_timestamp );
INSERT INTO order_records (id, year, month, day, customer_name, product_name, unit_price, qty, created_at) VALUES( 3, 2009, 10, 27, 'kaneko', 'orange B', 1.2, 8, current_timestamp );
INSERT INTO order_records (id, year, month, day, customer_name, product_name, unit_price, created_at) VALUES( 4, 2009, 10, 28, 'miyamoto', 'Apple L', 3, current_timestamp );
COMMIT;
データベースからログアウト
\q