SQLite Perl

SQLite3 用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 官方文档。

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

Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds.

Datasource has the form like : DBI:SQLite:dbname=’test.db’ SQLite is SQLite driver name and test.db is the name of SQLite database file. If the filename is given as ‘:memory:’, it will create an in-memory database in RAM that lasts only for the duration of the session.

If filename is actual device file name, then it attempts to open the database file by using its value. If no file by that name exists then a new database file by that name gets created.

You keep second and third paramter as blank strings and last parameter is to pass various attributes as shown below in the example.

2 $dbh->do($sql)

This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here $dbh is a handle returned by DBI->connect() call.

3 $dbh->prepare($sql)

This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object.

4 $sth->execute()

This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here, $sth is a statement handle returned by $dbh->prepare($sql) call.

5 $sth->fetchrow_array()

This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list.

6 $DBI::err

This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called.

7 $DBI::errstr

This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called.

8 $dbh->disconnect()

This routine closes a database connection previously opened by a call to 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
";

现在,让我们运行上面的程序在当前目录中,创建数据库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
";

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();

上述程序执行时,它会创建表公司test.db,它会显示以下消息:

Opened database successfully
Table created successfully

注意:任何操作情况下,看到下面的错误:

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

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

INSERT 操作

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
";

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   = "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
";

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   = "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
";

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   = "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
";

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

        原文作者:SQLite教程
        原文地址: https://www.yiibai.com/sqlite/sqlite_perl.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞