如果提示無效命令,可在perl/bin目錄下運行
二. 安裝DBD-MySQL模塊
從軟件下載中下載DBD-MySQL.zip,安裝方法同一.
三. 准備數據庫
啟動MySQL,首先創建一個數據庫mydata,然後創建一個表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)
輸入些數據:
MySQL> insert into address values (
-> 1,’Nighthawk’,’[email protected]’,92384092);
Query OK, 1 row affected (0.00 sec)
四. 下面用perl程序來插入若干記錄並做查詢.
use DBI;
#連接數據庫mydata
my $dbh = DBI->connect(’DBI:MySQL:mydata’) or dIE "無法連接數據庫: " . DBI->errstr;
print "插入若干記錄n";
my $sth = $dbh->prepare(q{
INSERT INTO address (id, name,email,telephone) VALUES (?, ?, ?, ?)
}) });
print "輸入記錄,回車結束:";
while ($inputdata =<>) {
chop $inputdata;
last unless($inputdata);
my ($id, $name,$email, $tel) = split( /,/, $inputdata);
$sth->execute($id, $name, $email,$tel)
}
# $dbh->commit;
print "下面根據輸入的名字打印出EMAIL地址和電話n";
my $sth = $dbh->prepare(’SELECT * FROM address WHERE name=?’)
or dIE $dbh->errstr;
print "請輸入姓名,回車結束:";
while ($inputname =<>) {
my @data;
chomp $inputname;
last unless($inputname);
$sth->execute($inputname) or dIE "錯誤: " . $sth->errstr;
while (@data = $sth->fetchrow_array()) {
print "Email:$datat Telephone:$datan";
}
}
#斷開連接
$dbh->disconnect;