位置:首頁 > 數據庫 > PostgreSQL教學 > PostgreSQL連接Perl

PostgreSQL連接Perl

安裝

PostgreSQL可以用Perl使用Perl DBI模塊,這是一個Perl編程語言的數據庫訪問模塊集成。它定義了一套方法,變數和約定,提供一個標準的數據庫接口。

下麵是簡單的步驟,Linux/Unix機器上安裝DBI模塊:

$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz
$ tar xvfz DBI-1.625.tar.gz
$ cd DBI-1.625
$ perl Makefile.PL
$ make
$ make install

如果需要安裝DBI的SQLite的驅動,那麼它可以被安裝如下:

$ wget http://search.cpan.org/CPAN/authors/id/T/TU/TURNSTEP/DBD-Pg-2.19.3.tar.gz
$ tar xvfz DBD-Pg-2.19.3.tar.gz
$ cd DBD-Pg-2.19.3
$ perl Makefile.PL
$ make
$ make install

在開始使用Perl的PostgreSQL的接口,需要在PostgreSQL安裝目錄中找到pg_hba.conf文件,並添加下麵一行:

# IPv4 local connections:
host    all         all         127.0.0.1/32          md5

可以使用下麵的命令啟動/重新啟動Postgres的服務器的如果它冇有運行:

[root@host]# service postgresql restart
Stopping postgresql service:                               [  OK  ]
Starting postgresql service:                               [  OK  ]

DBI 接口APIs

以下是重要的DBI例程,可以根據要求使用Perl程序操作SQLite數據庫。如果更複雜的應用程序,那麼可以看看到的Perl DBI官方文檔。

S.N. API & 描述
1 DBI->connect($data_source, "userid", "password", \%attr)

建立數據庫連接或會話,請求數據源。如果連接成功,則返回一個數據庫句柄對象。

數據源的形式如 : DBI:Pg:dbname=$database;host=127.0.0.1;port=5432 PG是PostgreSQL驅動程序名稱,testdb的數據庫的名稱。

2 $dbh->do($sql)

常規準備並執行一個SQL語句。返回受影響的行數或者undef錯誤。-1表示返回值的行數是不知道,不適用,或不可用。這裡的$dbh是DBI-> connect()調用返回的句柄。

3 $dbh->prepare($sql)

這為以後的執行程序準備一份聲明,由數據庫引擎,並返回一個引用語句句柄對象。

4 $sth->execute()

此例程執行任何處理是必要的執行準備好的語句。如果發生錯誤,將會返回undef。一個成功的執行總是返回true。這裡的$sth是$dbh->prepare($sql) 調用返回一個語句句柄。

5 $sth->fetchrow_array()

此例程讀取下一行的數據,並返回一個列表,其中包含的字段值。返回空字段為undef值在列表中。

6 $DBI::err

這相當於$h->err,$h為任何手柄類型,如$dbh, $sth或 $drh。返回從最後一個驅動方法,稱為本地數據庫引擎錯誤代碼。 

7 $DBI::errstr

這相當於$h->errstr,$h是任何手柄類型像$dbh, $sth或 $drh。這將返回本地數據庫引擎的錯誤消息,從最後DBI方法調用。 

8 $dbh->disconnect()

此例程關閉先前打開的數據庫連接,通過調用DBI->connect()。

連接到數據庫

下麵的Perl代碼顯示了如何連接到一個現有的數據庫。如果數據庫不存在,那麼它就會被創建,終於將返回一個數據庫對象。

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "Pg"; 
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) 
                      or die $DBI::errstr;

print "Opened database successfully
";

現在讓我們運行上麵的程序來打開我們的數據庫testdb中,如果成功打開數據庫,然後它會給下麵的消息:

Open database successfully

創建表

下麵的Perl程序將在以前創建的數據庫中創建一個表:

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "Pg"; 
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
                      or die $DBI::errstr;
print "Opened database successfully
";

my $stmt = qq(CREATE TABLE COMPANY
      (ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL););
my $rv = $dbh->do($stmt);
if($rv < 0){
   print $DBI::errstr;
} else {
   print "Table created successfully
";
}
$dbh->disconnect();

上述程序執行時,它會在數據庫testdb 創建COMPANY 表公司,它會顯示以下消息: 

Opened database successfully
Table created successfully

INSERT 操作

Perl程序,顯示我們如何在上麵的例子中創建COMPANY 表中的記錄:

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "Pg"; 
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
                      or die $DBI::errstr;
print "Opened database successfully
";

my $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES (1, 'Paul', 32, 'California', 20000.00 ));
my $rv = $dbh->do($stmt) or die $DBI::errstr;

$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES (2, 'Allen', 25, 'Texas', 15000.00 ));
$rv = $dbh->do($stmt) or die $DBI::errstr;

$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ));
$rv = $dbh->do($stmt) or die $DBI::errstr;

$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ););
$rv = $dbh->do($stmt) or die $DBI::errstr;

print "Records created successfully
";
$dbh->disconnect();

上述程序執行時,它會創建COMPANY表中的記錄,並會顯示以下兩行:

Opened database successfully
Records created successfully

SELECT 操作

Perl程序,表明我們如何獲取並顯示在上麵的例子中創建表COMPANY 中的記錄:

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "Pg"; 
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
                      or die $DBI::errstr;
print "Opened database successfully
";

my $stmt = qq(SELECT id, name, address, salary  from COMPANY;);
my $sth = $dbh->prepare( $stmt );
my $rv = $sth->execute() or die $DBI::errstr;
if($rv < 0){
   print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
      print "ID = ". $row[0] . "
";
      print "NAME = ". $row[1] ."
";
      print "ADDRESS = ". $row[2] ."
";
      print "SALARY =  ". $row[3] ."

";
}
print "Operation done successfully
";
$dbh->disconnect();

當上述程序執行時,它會產生以下結果:

Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY =  20000

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY =  15000

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY =  20000

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY =  65000

Operation done successfully

UPDATE 操作

Perl代碼顯示如何,我們可以使用UPDATE語句來更新任何記錄,然後從COMPANY 表獲取並顯示更新的記錄:

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "Pg"; 
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
                      or die $DBI::errstr;
print "Opened database successfully
";

my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);
my $rv = $dbh->do($stmt) or die $DBI::errstr;
if( $rv < 0 ){
   print $DBI::errstr;
}else{
   print "Total number of rows updated : $rv
";
}
$stmt = qq(SELECT id, name, address, salary  from COMPANY;);
my $sth = $dbh->prepare( $stmt );
$rv = $sth->execute() or die $DBI::errstr;
if($rv < 0){
   print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
      print "ID = ". $row[0] . "
";
      print "NAME = ". $row[1] ."
";
      print "ADDRESS = ". $row[2] ."
";
      print "SALARY =  ". $row[3] ."

";
}
print "Operation done successfully
";
$dbh->disconnect();

當上述程序執行時,它會產生以下結果:

Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY =  25000

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY =  15000

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY =  20000

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY =  65000

Operation done successfully

DELETE 操作

Perl代碼顯示了我們如何使用DELETE語句刪除任何記錄,然後獲取COMPANY 表並顯示剩餘記錄 :

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "Pg"; 
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
                      or die $DBI::errstr;
print "Opened database successfully
";

my $stmt = qq(DELETE from COMPANY where ID=2;);
my $rv = $dbh->do($stmt) or die $DBI::errstr;
if( $rv < 0 ){
   print $DBI::errstr;
}else{
   print "Total number of rows deleted : $rv
";
}
$stmt = qq(SELECT id, name, address, salary  from COMPANY;);
my $sth = $dbh->prepare( $stmt );
$rv = $sth->execute() or die $DBI::errstr;
if($rv < 0){
   print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
      print "ID = ". $row[0] . "
";
      print "NAME = ". $row[1] ."
";
      print "ADDRESS = ". $row[2] ."
";
      print "SALARY =  ". $row[3] ."

";
}
print "Operation done successfully
";
$dbh->disconnect();

當上述程序執行時,它會產生以下結果:

Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY =  25000

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY =  20000

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY =  65000

Operation done successfully