SoFunction
Updated on 2025-04-08

Perl Mysql database operation implementation code

1. Install the DBI module
Step 1:
Download it from the TOOLS column, and after downloading it, use winzip to unpack it into a temp directory. There are three files in total:
Readme


Step 2:
In the DOS window, run the following DOS command in the temp directory:
ppm install
If the command is not prompted, it can be run in the perl/bin directory
2. Install the DBD-Mysql module
Download from software download, the installation method is the same.
3. Prepare the database
Start mysql, first create a database mydata, and then create a table address
mysql> create database mydata;
Query OK, 1 row affected (0.00 sec)
mysql> use mydata;
Database changed
mysql> create table address (
-> id int(5) not null,
-> name varchar(40) not null,
-> email varchar(50) not null,
-> telephone int(12) null);
Query OK, 0 rows affected (0.05 sec)
Enter some data:
mysql> insert into address values (
-> 1,'Nighthawk','nighthawk@',92384092);
Query OK, 1 row affected (0.00 sec)
4. The following is the perl program to insert several records and query them.
use DBI;
#Connect the database mydata
my $dbh = DBI->connect('DBI:mysql:mydata') or die "Cannot connect to database: " . DBI->errrstr;
print "Insert several records\n";
my $sth = $dbh->prepare(q{
INSERT INTO address (id, name,email,telephone) VALUES (?, ?, ?, ?)
}) });
print "Enter record, enter end:";
while ($inputdata =<>) {
chop $inputdata;
last unless($inputdata);
my ($id, $name,$email, $tel) = split( /,/, $inputdata);
$sth->execute($id, $name, $email,$tel)
}
# $dbh->commit;
print "The following prints the EMAIL address and phone number based on the entered name\n";
my $sth = $dbh->prepare('SELECT * FROM address WHERE name=?')
or die $dbh->errstr;
print "Please enter your name and enter to end:";
while ($inputname =<>) {
my @data;
chomp $inputname;
last unless($inputname);
$sth->execute($inputname) or die "Error: " . $sth->errstr;
while (@data = $sth->fetchrow_array()) {
print "Email:$data[2]\t Telephone:$data[3]\n";
}
}
#Disconnect
$dbh->disconnect;
Nighthawk