四、perl进行MySQL开发实例
上述都安装完后,就可以进行实际开发了。
首先在test数据库中新建一个表
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)
简单的perl代码实例:
#!perl
use DBI;
my $db = "test";
my $host = "localhost";
my $user = "root";
my $pwd = "";
my $connection="dbi:mysql:$db:$host";
my $dbh = DBI->connect($connection,$user,$pwd) or die "failed to connect mysql,$!";
print "插入若干记录\n";
my $sql = "insert into address(id,name,email,telephone) values(?,?,?,?)";
my $sth = $dbh->prepare($sql);
print "输入记录,回车结束:";
while ($inputdata =<>) {
chomp $inputdata;
last unless($inputdata);
my ($id, $name,$email, $tel) = split( /,/, $inputdata);
$sth->execute($id, $name, $email,$tel);
}
# $dbh->commit;
print "下面根据输入的名字打印出EMAIL地址和电话\n";
$sql = "SELECT * FROM address WHERE name=?";
$sth = $dbh->prepare($sql) 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()) {
print "Email:$data[2]\t Telephone:$data[3]\n";
}
}
#断开连接
$sth->finish();
$dbh->disconnect();