Perl Programming Page 4 - SQL and CGI with Perl and DBI |
Any SQL query is possible using DBI. This includes table joins. Let’s modify the previous example showinstruments2.pl and perform a table join as shown here in showinstrument3.pl: #!/usr/bin/perl -w use strict; my($who, $instrument); print "Enter name of musician and I will show you his/her instruments: "; my $dbh = DBI->connect("DBI:mysql:musicians_db", "musicfan", "CrimsonKing"); die "connect failed: " . DBI->errstr() unless $dbh; # use a table join to query the instrument names $sth->execute($who) or die "execute failed: " . $sth->errstr(); # loop through them, printing them $sth->finish(); $dbh->disconnect(); The big change is the preparation and execution of the query: # use a table join to query the instrument names $sth->execute($who) or die "execute failed: " . $sth->errstr(); Here we construct one large query as we did previously in this chapter. It joins themusicians,what_they_play, andinstrumentstables. Notice how we are using a placeholder when we comparemusicians.nameand how the variable$whois provided within theexecute()method. Does this table join work? Yep. $ perl showinstruments3.pl Perl andDBIallow us to easily create programs that query our database. This means we can do anything with Perl that we can do with the SQL database including many SQL commands that we have not talked about in this chapter.
blog comments powered by Disqus |
|
|
|
|
|
|
|