簡介如下
建置環境 : CentOS v6.2
程式語言 : Perl v5.10.1
一開始需先安裝 FreeTDS 程式,但是 yum 預設並沒有這個套件,所以要先前置作業下載 CentOS epel RPM , 記得看你的 CentOS 版本是 5 還是 6 找到對應的目錄去下載
安裝步驟
1. sudo su -
2. rpm -Uvh epel-release-6-8.noarch.rpm
3. vim /etc/yum.repos.d/epel.repo,把 [epel] 裡面的註解取消
4. yum update
5. yum install freetds.x86_64
6. yum install freetds-devel.x86_64
7. vim /etc/freetds.conf,新增如下
[SQLSERVER]
host = your_sqlserver_hostname
port = 1433
tds version = 7.0
安裝完成後可以先執行 tsql 測試
tsql -S sqlserver.hostname.com -U sqlusername -D your_db_name
進去後再下
select * from sys.Tables;
GO
quit
也可以改成 "一行執行"
printf "SELECT * FROM httpstatus\ngo\n" | tsql -S sqlserver.hostname.com -U sqlusername -P sqlpassword -D your_db_name
前置作業完成後,再來要安裝 Perl 模組 DBD::Sybase,你沒看錯真的是 Sybase 模組(緣由請參考這裡)
安裝步驟
1. export SYBASE=/usr (這行要有不然安裝時會出現找不到 sybase library 錯誤)
2. cpanm DBD::Sybase
都完成後終於要開始寫程式啦, 程式碼如下
#!/usr/bin/perl
#use lib ('./modules');
use DBI;
use DBD::Sybase;
my $database = "your_db_name";
my $username = 'sqlusername';
my $password = 'sqlpassword';
#SQLSERVER 字串對應至 /etc/freetds.conf 裡面的 [SQLSERVER] tag
$dsn = "DBI:Sybase:server=SQLSERVER;database=$database";
my $dbh = DBI->connect($dsn, $username, $password) or die "Database connection not made : $DBI::errstr";
my $sql = "SELECT TOP 5 * FROM httpstatus order by testtime desc";
my $sth = $dbh->prepare( $sql );
$sth->execute() or die "unable to execute query $sql, error $DBI::errstr\n";
$rows = $sth->rows;
while ( @first = $sth->fetchrow_array ) {
foreach $field (@first) {
print "$field ";
}
print "\n";
}
$sth->finish();
undef $sth;
$dbh->disconnect();
print "Query successfully\n";
資考資料 : http://dolio.lh.net/~apw/doc/HOWTO/HOWTO-Connect_Perl_to_SQL_Server.pdf