打算熟悉下perl,自然主要用於資料庫管理和監控方面的,所以需要連線資料庫。Perl連線資料庫可以通過DBI模組和相應資料庫的DBD驅動,上一篇記錄了DBI模組的安裝,這裡記錄下DBD::mysql驅動的安裝。可以從CPAN下載相應DBD驅動。
安裝過程很簡單,下載解壓:
tar xvf DBD-mysql-4.006.tar
然後進入DBD-mysql-4.006目錄,執行:
make
make test
make install
檢查已經安裝好的Perl模組:
DBD::mysql
DBI
Perl
安裝DBD::mysql需要mysql_config,包含在Headers and libraries安裝包中(MySQL-devel-community-5.1.23-0.rhel4.i386.rpm),並且PATH環境變數中必須包含mysql_config所在的路徑。否則在執行perl Makefile.PL生成makefile的時候會報錯:
Can’t exec “mysql_config”: No such file or directory at Makefile.PL line 76.
Cannot find the file ‘mysql_config’! Your execution PATH doesn’t seem
not contain the path to mysql_config. Resorting to guessed values!
Can’t exec “mysql_config”: No such file or directory at Makefile.PL line 466.
安裝好DBI和DBD::mysql後,就可以訪問MySQL資料庫啦,首先在test庫中建立一個table:
然後執行下面的Perl指令碼插入一條資料並且查詢得到結果:
use DBI;
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost","NinGoo","password", {'RaiseError' => 1});
my $rows = $dbh->do("INSERT INTO test (id, name) VALUES (1, 'NinGoo')");
my $query = $dbh->prepare("SELECT name FROM test");
$query->execute();
while(my $rs = $query->fetchrow_hashref()) {
print "$rs->{'name'}\n";
}