Skip to content

Instantly share code, notes, and snippets.

@oshiro-kazuma
Created June 30, 2012 01:22
Show Gist options
  • Save oshiro-kazuma/3021679 to your computer and use it in GitHub Desktop.
Save oshiro-kazuma/3021679 to your computer and use it in GitHub Desktop.
DBIに入門した
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use DBI;
my $database = 'test.db';
my $data_source = "dbi:SQLite:dbname=$database";
my $dbh = DBI->connect($data_source);
# 引数の値をInsert
if(scalar(@ARGV) == 2) {
main();
# テーブルのデータを表示
} elsif($ARGV[0] eq "show" && scalar(@ARGV) == 1) {
my @date = findAll();
show(@date);
# テーブル作成
} elsif($ARGV[0] eq "create" && scalar(@ARGV) == 1) {
$dbh->do('create table books (title,author);');
print "crete table books.\n";
# テーブル削除
} elsif($ARGV[0] eq "drop" && scalar(@ARGV) == 1) {
$dbh->do('drop table books;');
print "drop table books.\n";
# Usage表示
} else {
print "Usage: \n";
print " Insert : dbi_test.pl 'title' 'author'\n";
print " Show Table : dbi_test.pl show\n";
print " Drop Table : dbi_test.pl drop\n";
print " Create Table : dbi_test.pl create\n";
exit(1);
}
exit(0);
sub main {
# Insert処理
insert($ARGV[0], $ARGV[1]);
# とりあえず表示
my @date = findAll();
show(@date);
$dbh->disconnect;
}
sub show {
my(@date) = @_;
for(my $i = 0; $i < scalar(@{$date[0]}); $i++) {
print $i, " ";
print $date[0][$i][0], " ";
print $date[0][$i][1], " \n";
}
}
sub insert {
# これでいける
(my $title, my $author) = @_;
my $sth = $dbh->prepare('insert into books(title, author) values(?, ?); ');
$sth->execute($title, $author);
}
sub findAll {
my $select = "select * from books;";
return $dbh->selectall_arrayref($select);
}
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use DBI;
# sqlite使ってる
my $dbh = DBI->connect("dbi:SQLite:dbname=test.db");
# Insert処理
$dbh->prepare('insert into books(title, author) values(?, ?); ')
->execute("タイトル", "著者");
# Select処理
my $sth = $dbh->prepare("select * from books;");
$sth->execute;
# とりあえず表示
while (my @row = $sth->fetchrow_array) {
print join(', ', @row), "\n";
}
$dbh->disconnect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment