在 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; |