在 Perl 要連接資料庫可以使用 DBI module, DBI module 支援多種資料庫系統, 例如 DB2, MS SQL Server, Oracle, SQLite, PostgreSQL, Firebird 及 MySQL。只要在程式宣告使用 DBI module, 用 Perl 連接 MySQL 便會跟 PHP 一樣簡單, 以下是使用例子:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#!/usr/bin/perl use strict; use warnings; use DBI; ### MySQL connect details my $db = "db_name"; my $host = "localhost"; my $username = "username"; my $password = "password"; ### connect to MySQL database my $dbh = DBI->connect ("DBI:mysql:database=$db:host=$host", $username, $password) or die "Could not connect to database: $DBI::errstr\n"; ### SQL query here my $sth = $dbh->prepare("SELECT * FROM table"); ### execute the query $sth->execute( ); ### get the results from MySQL and print print "\tMySQL results:\n================================================\n"; while ( my @row = $sth->fetchrow_array( ) ) { print "@row\n"; } exit; |