9. SQL Select
SELECT * FROM address;
-- show everything
SELECT *
FROM address
WHERE state='FL';
-- only florida
SELECT first_name, last_name
FROM address
WHERE state='FL';
-- specific fields
10. SQL Delete
DELETE FROM address;
-- very dangerous
-- deletes everything
DELETE FROM address
WHERE state='FL';
-- use a WHERE condition
13. prepare/execute/fetch
$sth = $dbh->prepare ("
SELECT id, first_name, last_name, city, state
FROM address
WHERE city=?
AND state=?
");
$sth->execute ('Sacramento', 'CA');
# fills in values to the ? placeholders
while (my $row = $sth->fetch()) {
my ($id, $first_name, $last_name, $city, $state) = @$row;
print "$city, $state: $first_name $last_namen";
}
14. Placeholder
?
Security: The placeholder escapes data
– Counters SQL injection attack
Optimization: Prepare once, execute many. Sometimes faster.
– MySQL: no difference
– Oracle: faster
16. fetchall_arrayref()
# No WHERE condition. Get everything.
$sth = $dbh->prepare ("
SELECT id, first_name, last_name, city, state
FROM address
");
$sth->execute ();
my $rows = $sth->fetchall_arrayref();
foreach my $row (@$rows) {
my ($id, $first_name, $last_name, $city, $state) = @$row;
print "$city, $state: $first_name $last_namen";
}
17. No fetch
$sth = $dbh->prepare ("
INSERT INTO address (first_name, last_name, city, state)
VALUES (?,?,?,?)
");
$sth->execute('Doug', 'Engelbart', 'Moscow', 'Idaho');
18. No fetch
$sth = $dbh->prepare ("
UPDATE address SET state=?
WHERE city=?
");
$sth->execute ('TN', 'Moscow');
19. No fetch
$sth = $dbh->prepare ("
UPDATE address SET first_name=?, last_name=?
WHERE city=? AND state=?
");
$sth->execute ('Edgar', 'Codd', 'TN', 'Moscow');
20. No fetch
$sth = $dbh->prepare ("
DELETE FROM address
WHERE city=? AND state=?
");
$sth->execute ('Moscow', 'TN');
21. last_insert_id()
# after your INSERT statement
my $row_id = $dbh->last_insert_id(
undef, undef, undef, undef
);
print "row_id: $row_idn";
22. Caching the dbh
Opening a database connection incurs overhead.
You want to cache the database handle
– Open once.
– Keep it open.
Example of caching on next slide
23. state
use feature 'state'; # perl 5.10
sub get_dbh {
state $dbh;
if (!$dbh) {
$dbh = DBI->connect(
"dbi:SQLite:dbname=address.db", "", ""
);
}
return $dbh;
}