SQLite – Perl

SQLite – Perl


在本章中,您将学习如何在 Perl 程序中使用 SQLite。

安装

SQLite3 可以使用 Perl DBI 模块与 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/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz
$ tar xvfz DBD-SQLite-1.11.tar.gz
$ cd DBD-SQLite-1.11
$ perl Makefile.PL
$ make
$ make install

DBI 接口 API

以下是重要的 DBI 例程,它们可以满足您从 Perl 程序使用 SQLite 数据库的要求。如果您正在寻找更复杂的应用程序,那么您可以查看 Perl DBI 官方文档。

Sr.No. API & 描述
1

DBI->connect($data_source, “”, “”, \%attr)

建立到请求的 $data_source 的数据库连接或会话。如果连接成功,则返回数据库句柄对象。

数据源的格式如下 – DBI:SQLite:dbname = ‘test.db’其中 SQLite 是 SQLite 驱动程序名称,test.db 是 SQLite 数据库文件的名称。如果文件名指定为‘:memory:’,它将在 RAM 中创建一个仅在会话期间持续的内存数据库。

如果文件名是实际设备文件名,则它会尝试使用其值打开数据库文件。如果不存在具有该名称的文件,则会创建具有该名称的新数据库文件。

您将第二个和第三个参数保留为空字符串,最后一个参数用于传递各种属性,如下例所示。

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   = "SQLite"; 
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) 
   or die $DBI::errstr;

print "Opened database successfully\n";

现在,让我们运行上面的程序在当前目录中创建我们的数据库 test.db。您可以根据需要更改路径。将上面的代码保存在 sqlite.pl 文件中,并按如下所示执行它。如果数据库创建成功,那么它将显示以下消息 –

$ chmod +x sqlite.pl
$ ./sqlite.pl
Open database successfully

创建表

下面的 Perl 程序用于在之前创建的数据库中创建一个表。

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
   or die $DBI::errstr;
print "Opened database successfully\n";

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\n";
}
$dbh->disconnect();

执行上述程序时,它将在您的 test.db 中创建 COMPANY 表,并显示以下消息 –

Opened database successfully
Table created successfully

注意– 如果您在任何操作中看到以下错误 –

DBD::SQLite::st execute failed: not an error(21) at dbdimp.c line 398

在这种情况下,打开DBD-SQLite 安装中可用的dbdimp.c 文件并找出sqlite3_prepare()函数并将其第三个参数更改为-1而不是 0。最后,使用make安装 DBD::SQLite并执行make install以解决问题。

插入操作

下面的 Perl 程序显示了如何在上面示例中创建的 COMPANY 表中创建记录。

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
   or die $DBI::errstr;
print "Opened database successfully\n";

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\n";
$dbh->disconnect();

执行上述程序时,它将在 COMPANY 表中创建给定的记录,并显示以下两行 –

Opened database successfully
Records created successfully

选择操作

下面的 Perl 程序显示了如何从上面示例中创建的 COMPANY 表中获取和显示记录。

#!/usr/bin/perl

use DBI;
use strict;

my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
   or die $DBI::errstr;
print "Opened database successfully\n";

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] . "\n";
      print "NAME = ". $row[1] ."\n";
      print "ADDRESS = ". $row[2] ."\n";
      print "SALARY =  ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$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

更新操作

以下 Perl 代码显示了如何使用 UPDATE 语句更新任何记录,然后从 COMPANY 表中获取并显示更新的记录。

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
   or die $DBI::errstr;
print "Opened database successfully\n";

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\n";
}
$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] . "\n";
      print "NAME = ". $row[1] ."\n";
      print "ADDRESS = ". $row[2] ."\n";
      print "SALARY =  ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$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

删除操作

以下 Perl 代码显示了如何使用 DELETE 语句删除任何记录,然后从 COMPANY 表中获取并显示剩余的记录 –

#!/usr/bin/perl

use DBI;
use strict;

my $driver   = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
   or die $DBI::errstr;
print "Opened database successfully\n";

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\n";
}

$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] . "\n";
      print "NAME = ". $row[1] ."\n";
      print "ADDRESS = ". $row[2] ."\n";
      print "SALARY =  ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$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

觉得文章有用?

点个广告表达一下你的爱意吧 !😁