1. connecting to MySQL
#!C:/Perl/bin/perl
use DBI;
use strict;
my $driver = "mysql";
my $database = "academia";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "The_password";
my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;
2. Select operation
my $sth = $dbh->prepare("SELECT * FROM PHYSICISTS
WHERE phys_id > 105");
$sth->execute() or die $DBI::errstr;
my $nb_rows = $sth->rows;
print "Number of rows found : $nb_rows";
print "\n";
while (my @row = $sth->fetchrow_array()) {
my ($phys_id,$first_name,$last_name,$birth_date,$death_date,$discipline) = @row;
print " Id = $phys_id. First name = $first_name. Last name = $last_name.
Birth day = $birth_date. Death date = $death_date. Discipline = $discipline.\n";
}
$sth->finish();
# $sth This key word stands for "Statement handle object".
3. Related ouput
Outputs:
C:\www\PERL>perl database_2.pl
Number of rows found : 4
Id = 106. First name = Louis. Last name = DeBroglie.
Birth day = 1892. Death date = 1987. Discipline = wave_mechanics.
Id = 107. First name = Erwin. Last name = Schrodinger.
Birth day = 1887. Death date = 1961. Discipline = quantum_mechanics.
Id = 108. First name = Maurice. Last name = Dirac.
Birth day = 1902. Death date = 1984. Discipline = atomic.
Id = 109. First name = Ludwig. Last name = Boltzmann.
Birth day = 1844. Death date = 1906. Discipline = stat_physics.
The SQL "SELECT" statement is done by using the API prepare() function.
The result is stored in the key word $sth (Statement handle object), and
then executed by using the API function execute(). This Stattement handle
is released by the API function finish().
The API function fetchrow_array() fetches all the results one by one
and printing those results.
|