プレースホルダによるパラメータ変更
プレースホルダを使用する
sample.pl
# プラグマ
use strict;
use warnings;
# DBI定義
use DBI qw(:sql_types);;
########################################
# データ取得方法3
########################################
sub select_db
{
# パラメータ取得
my ($sth) = @_;
# レコード数を取得
my $num_rows = $sth->rows;
print "該当 $num_rows 件\n";
# ハッシュのリファレンスを取得
while ( my $hash_ref = $sth->fetchrow_hashref ){
print "id=$hash_ref->{code}, name=$hash_ref->{value} memo=$hash_ref->{biko} \n";
}
}
my $user = 'root';
my $passwd = '';
my $dbname = 'test01';
my $host = 'localhost';
my $db = DBI->connect("DBI:mysql:$dbname:$host", $user, $passwd);
# SELECT実行
my $sth = $db->prepare("select * from table01 where code = ? or code = ?");
my $item1 = 1;
my $item2 = 6;
# バインド
$sth->bind_param(1, $item1, DBI::SQL_INTEGER);
$sth->bind_param(2, $item2, DBI::SQL_INTEGER);
# 実行
$sth->execute;
# 前取得
print "前データ\n";
select_db($sth);
print "\n";
# UPDATE実行
my $sth2 = $db->prepare("update table01 set value = ? , biko = ? where code = ?");
# 変数設定
my $item10 = "6";
my $item11 = "fffff";
my $item12 = "sample test";
# バインド
$sth2->bind_param(1, $item11, DBI::SQL_VARCHAR);
$sth2->bind_param(2, $item12, DBI::SQL_VARCHAR);
$sth2->bind_param(3, $item10, DBI::SQL_INTEGER);
# 実行
$sth2->execute;
# SELECT実行
my $sth3 = $db->prepare("select * from table01 where code in(?, ?)");
# 変数設定
my $item31 = "1";
my $item32 = "6";
# バインド
$sth3->bind_param(1, $item31, DBI::SQL_INTEGER);
$sth3->bind_param(2, $item32, DBI::SQL_INTEGER);
# 実行
$sth3->execute;
# 追加後取得
print "追加後データ\n";
select_db($sth3);
print "\n";
$sth->finish;
$db->disconnect;
0;
# 処理開始
BEGIN {
print "test-script-start\n";
}
# 処理終了
END {
print "test-script-end\n";
}
結果
>perl sample.pl
test-script-start
前データ
該当 2 件
id=1, name=aaaaa memo=
id=6, name=xxxxxxxxxxxxxxxxxxx memo=zzzzzzzzzzzzzzzzz
追加後データ
該当 2 件
id=1, name=aaaaa memo=
id=6, name=fffff memo=sample test
test-script-end
D:\Tools\Works\perl>
最終更新:2012年01月21日 20:45