用perl訪問mysql資料庫(轉)

post0發表於2007-08-10
用perl訪問mysql資料庫(轉)[@more@]

一. 安裝DBI模組

步驟1:

從TOOLS欄目中下載DBI.zip,下載完後用winzip解開到一個temp目錄,共有三個檔案:

Readme

DBI.ppd

DBI.tar.gz

步驟2:

在DOS視窗下,temp目錄中執行下面的DOS命令:

ppm install DBI.ppd

如果提示無效命令,可在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’,’nighthawk@163.net’,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:$data[2]t Telephone:$data[3]n";

}

}

#斷開連線

$dbh->disconnect;

Nighthawk 版權所有,轉載請保留署

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/8225414/viewspace-943045/,如需轉載,請註明出處,否則將追究法律責任。

相關文章