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

    点赞