#!c:/Perl/bin/perl.exe use strict; use DBI(); print "Content-type: text/plain; charset=iso-8859-1\n\n"; # Connect to the database. my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost", "testuser", "testpassword", { 'RaiseError' => 1 }); # Drop table 'foo'. This may fail, if 'foo' doesn't exist. # Thus we put an eval around it. print "DROP the foo table if it exists...\n"; eval { $dbh->do("DROP TABLE foo") }; print "Dropping foo failed: $@\n" if $@; # Create a new table 'foo'. This must not fail, thus we don't # catch errors. $dbh->do("CREATE TABLE foo (id INTEGER, name VARCHAR(20))"); print "INSERT 2 rows...\n"; # INSERT some data into 'foo'. We are using $dbh->quote() for # quoting the name. $dbh->do("INSERT INTO foo VALUES (1, " . $dbh->quote("Jan") . ")"); # Same thing, but using placeholders $dbh->do("INSERT INTO foo VALUES (?, ?)", undef, 2, "Berit"); print "INSERT a 3rd row...\n"; $dbh->do("INSERT INTO foo VALUES (?, ?)", undef, 3, "JB"); print "SELECT the 3 rows...\n"; # Now retrieve data from the table (3 rows). my $sth = $dbh->prepare("SELECT * FROM foo"); $sth->execute(); while (my $ref = $sth->fetchrow_hashref()) { print "Found a row: id = $ref->{'id'}, name = $ref->{'name'}\n"; } $sth->finish(); print "UPDATE the 3rd row, from 'JB' to 'JanBerit'...\n"; $dbh->do("UPDATE foo SET name = 'JanBerit' WHERE name = 'JB' LIMIT 1"); print "SELECT the 3 rows...\n"; # Now retrieve data from the table (3 rows). my $sth = $dbh->prepare("SELECT * FROM foo"); $sth->execute(); while (my $ref = $sth->fetchrow_hashref()) { print "Found a row: id = $ref->{'id'}, name = $ref->{'name'}\n"; } $sth->finish(); print "DELETE the 3rd row...\n"; $dbh->do("DELETE FROM foo WHERE name = 'JanBerit' LIMIT 1"); print "SELECT the 2 rows...\n"; # Now retrieve data from the table (2 rows). my $sth = $dbh->prepare("SELECT * FROM foo"); $sth->execute(); while (my $ref = $sth->fetchrow_hashref()) { print "Found a row: id = $ref->{'id'}, name = $ref->{'name'}\n"; } $sth->finish(); # Disconnect from the database. $dbh->disconnect();