SQLite
- SQLite3をインストール
- DBD::SQLiteをインストール
- DBをtest.dbという名前で作成
use DBI; my $db_name = 'test.db'; my $dbh = DBI->connect("dbi:SQLite:dbname=$db_name",'','',{AutoCommit=>0}); my $table_name = 'test_t'; #テーブル作成 { my $sth = $dbh->prepare(qq{create table $table_name (id integer primary key,name text not null)}); $sth->execute; } # insert する名前リスト my @insert_values = qw( fn1 fn2 fn3 fn4 fn5 fn6 fn7 ); # insert 処理 { my $sth = $dbh->prepare(qq{insert into $table_name (name) values (?)}); foreach(@insert_values){ $sth->execute($_); } } # 取得してみる { my $sth = $dbh->prepare(qq{select id,name from $table_name}); $sth->execute; my ($id,$name); $sth->bind_columns(?($id,$name)); while($sth->fetch){ print "$id,$name?n"; } } # fn0から fn4 までをnanashiにする { my $sth = $dbh->prepare(qq{update $table_name set name = 'nanashi' where name = ?}); for(my $i=0;$i<4;$i++){ $sth->execute("fn$i"); } } # 再度取得してみる { my $sth = $dbh->prepare(qq{select id,name from $table_name}); $sth->execute; my ($id,$name); print "0 から 3 は nanashi のはず?n"; $sth->bind_columns(?($id,$name)); while($sth->fetch){ print "$id,$name?n"; } } $dbh->commit;
テーブル名とテーブル定義を受けとると
テーブル作成のSQLを返す関数を作っておくと便利かも。
全ての仕様を見たすものを作れるほど勉強してないので、ご容赦ください。
my $table_define = [ {col=>'id',type=>'integer primary key'}, {col=>'name',type=>'text not null'}, ]; sub sql_create_table{ my $table_name = shift; my $define = shift; return sprintf qq{create table $table_name (%s)},join(',',map {$_->{col}.' '.$_->{type}} @$define); }
- サーバセッティングとか考えなくてよいので楽。
- DB が 1ファイルになっているので、手軽。ただし大規模データベースにはむかない。
- たとえSQLインジェクションされても被害が他のDBに及ばない。
- 他のRDBMSに比べて機能が貧弱(使える関数が少ない,参照整合性制約はないらしい、、、)