my ($age) = $sth->fetchrow_array(); return $age; } }
也就是只 prepare 一次, 然后多次使用, prepare 的开销一般比较大.
或者直接用 prepare_cached, 其会检查这一次查询是不是和上一次一样:
1 2 3 4 5 6 7 8 9 10 11 12 13
subage_by_id{ # Arguments: database handle, person ID number my ($dbh, $id) = @_; my $sth = $dbh->prepare_cached('SELECT age FROM people WHERE id = ?') ordie"Couldn't prepare statement: " . $dbh->errstr;
subnew_employee{ # Arguments: database handle; first and last names of new employee; # department ID number for new employee's work assignment my ($dbh, $first, $last, $department) = @_; my ($insert_handle, $update_handle);
my $insert_handle = $dbh->prepare_cached('INSERT INTO employees VALUES (?,?,?)'); my $update_handle = $dbh->prepare_cached('UPDATE departments SET num_members = num_members + 1 WHERE id = ?');
die"Couldn't prepare queries; aborting" unlessdefined $insert_handle && defined $update_handle;
my $dbh = DBI->connect("dbi:mysql:dbname=test;host=localhost", "user", "password") ordie"Couldn't connect to database: " . DBI->errstr;
# 创建表 $dbh->do(qq{ CREATE TABLE IF NOT EXISTS mytable ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, value TEXT NOT NULL, ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id) ) });