EvoTalk

24 六月, 2009

Perl Connect MS SQL Server 2005 Express

Posted by: asd In: Code Snippet| Perl| 程式設計 ()

先安裝需用到的 module
#ppm-shell
#install DBI
#install DBD-ODBC

PERL:
  1. #!/usr/bin/perl -w
  2. use strict; # 使用變數前一定要定義
  3. use DBI; # 使用DBI模組, 連結資料庫
  4. use DBD::ODBC;
  5.  
  6. my $server='localhost\SQLEXPRESS';
  7. my $database="your_db";
  8. my $user="sa";
  9. my $password="123456";
  10. my $DSN = "driver={SQL Server};Server=$server;database=$database;uid=$user;pwd=$password;";
  11. my $dbh = DBI->connect("dbi:ODBC:$DSN", { RaiseError => 1, AutoCommit => 1 }) || die "Can't connect: $DBI::errstr\n";
  12.  
  13. # 執行 sql 敘述
  14. my $sql_statement = "select * from user_data";
  15. my $sth = $dbh->prepare($sql_statement) || die "Can't prepare the SQL statement: $DBI::errstr\n";
  16. $sth->execute || die "Can't execute the SQL statement: $DBI::errstr\n";
  17.  
  18. # 顯示欄位名稱
  19. print "$sth->{NAME}->[0]\n";
  20. print "$sth->{NAME}->[1]\n";
  21. print "$sth->{NAME}->[2]\n";
  22. print "$sth->{NAME}->[3]\n";
  23.  
  24. # 讀取紀錄
  25. #while (my @row = $sth->fetchrow_array)
  26. #{
  27. #       print "@row\n";
  28. #}
  29.  
  30. while(my $ref = $sth->fetchrow_hashref())
  31. {
  32. foreach my $field ( keys %{ $ref } )
  33. {
  34. print "$field: $ref->{ $field }\n";
  35. }
  36. }
  37.  
  38. # 刪除資料物件,關閉連線
  39. $sth->finish;
  40. $dbh->disconnect;

Tags:

Releated Posts



No Responses to "Perl Connect MS SQL Server 2005 Express"

Comment Form