うさこ: 2007年5月アーカイブ

Postgresでデータベースを作るときの文字コード設定
データベースごとに文字コードを変えることが可能。

createdb データベース名 --encoding unicode
とか
createdb データベース名 -E UTF-8

古いバージョンで上記が効かないならオプション位置を前に変えたら動くかも。

createdb -E UTF-8 データベース名

■select(取り出す)
select * from テーブルの名前 where status='xxx' order by id;

statusの値がxxxデータをidの順に取り出します。order by id descだと、大きい順。
limit 2だと2個だけ。(PostgreSQL特有)
offset10だと10番目から(PostgreSQL特有)
取り出すデータは*(全部)です。(もちろん指定できる)

□便利な応用
select count(*) from テーブルの名前 where created > '2009-01-01';
2009年1月1日以降のデータの数を取得

■insert(登録する)
insert into DBの名前 values(データ1,データ2,データ3);

□実際のところ
insert into DBの名前 values(データ1,データ2,データ3);
insert into DBの名前 values(データ1,データ2,データ3);
......
とかかれたテキストファイル_insert_table1.sqlを作ってしまって、
psql -d DB名 -f _insert_table1.sql
で実行した方が楽、だし確実(実行したものが残せるし)。

■update(データ更新)
update テーブルの名前 set status = '×××' where id='xxx'

idの値がxxxの箇所のfileの値を×××にします。

■delete(データ削除)
delete from テーブルの名前 where id='xxx'

放っておくとごみがたまります。
/usr/bin/vacuumdb/vacuumdb -a -z
を毎日。
/usr/bin/vacuumdbvacuumdb -a -f
を月一回程度。

確認は
/usr/bin/vacuumdb/vacuumdb -a -z >! /tmp/vacuumdb_result.txt
/tmp/vacuumdb_result.txt
にVACUUMと記録されたらOK

■cronで自動化
postgres権限でcronetabを編集
emacs crontab

内容
00 3 * * * /usr/bin/vacuumdbvacuumdb -a -z
00 3 1 * * /usr/bin/vacuumdbvacuumdb -a -f

毎日午前3時と、毎月1日の午前3時に行われます。