Microsoft Word - Sam's Teach Yourself MySQL in 21 Days - SAMS.doc

(singke) #1
my $dbh = DBI->connect($driver:database=$database, "root", "tacobell")
or die "Can't connect";

# Insert the values
$dbh->do("INSERT INTO Customers (First_Name, Last_Name)
VALUES ('Renee', 'Robertson')");
$dbh->do("INSERT INTO Customers (First_Name, Last_Name)
VALUES ('Larry', 'Isacson')");
$dbh->do("INSERT INTO Customers (First_Name, Last_Name)
VALUES ('Mark', 'Harrison')");

# Disconnect from the database
$dbh->disconnect;

exit;
Take a line-by-line look at the anatomy of this script. The first line tells where the Perl interpreter is
found. This allows you to execute this program without explicitly calling the Perl interpreter. The next
line tells the interpreter to use the DBI module. If you forget this line, the rest of your code will not work.
You start to build the connection string in the next two lines. You will see this technique used a lot. It
allows you to change things quickly in the future or let you build your connection string based on
command-line arguments. The next line is where you actually connect to the database. The or die
statement is the minimum amount of error checking you can provide. There is more you can use, and
they are available in the man pages. The next few lines add the records to the Customers table in the
database. The next line disconnects you from the database and destroys your handle. The final line tells
the interpreter that it has reached the end of the script.

As you can see, the process is very simple and straightforward. In the previous code sample, you saw
how two of the three functions of the database handle object were used. Now take a look at the third
function.
The prepare() method of the database handle object is different from the other two methods in the
database handle. This method returns a statement handle. The statement handle has its own set of
methods and properties. The following are some of these methods:
ƒ execute() This method carries out the SQL statement that was issued in the
prepare() method of the database handle object.
ƒ fetchrow_hashref() This method returns an associative array containing the
values of the result set in a name=value pair relationship.
ƒ finish() This method destroys the statement handle and frees resources.
ƒ rows() This method returns the number of rows the statement contains.
Listing 14.1 is an example of how to use the prepare() method to generate a statement handle.
Listing 14.1 The Prepare Statement and the Statement Handle


10 #!/usr/bin/perl –w


20 use DBI;


30 $DSN = "DBI:mysql:database=Meet_A_Geek";


40 my $dbh = DBI->connect($DSN, "root", "tacobell")


50 or die "Can't connect";

Free download pdf