Sqlite是一个小巧的嵌入式关系型数据库,几乎可以嵌入所有编程语言,特别是C,C++,PHP,Perl等。这里就介绍如何用Perl连接并操作Sqlite数据库。
use DBI; # perl用以操作sqlite的模块,有这一个模块就足够了
use strict; # 初学必须加上这一句,以严格要求语句的撰写
use warnings;
main:
{
my $dbargs = {AutoCommit => 0, #使用事件
PrintError => 1};
# 连接到数据库
my $dbh = DBI->connect("dbi:SQLite:dbname=test.db","","",$dbargs);
# 创建表
$dbh->do("create table test(id int primary key, age, name)");
# 插入数据
$dbh->do("insert into test values(Null,'34','Liu Qiang'");
#更新数据
$dbh->do("update test set age='33' where name='Liu Qiang'");
#删除数据
$dbh->do("delete from test where name='Liu Qiang'");
#查询数据
my $sql = "SELECT * FROM test";
my $dbconn = $dbh->prepare($sql);
$dbconn->execute();
my (@row_ary,$cc,$bb,$dd);
while (@row_ary = $dbconn->fetchrow_array ){
my($cc,$bb,$dd) = @row_ary;
print "表Test的内容为\n";
print "\t@row_ary\n";
}
#删除表
#$dbh->do("drop table test");
#清空表,表结构还存在
$dbh->do("delete from test");
if ($dbh->err()) { die "$DBI::errstr\n"; } #连接错误提示
$dbh->commit();
$dbh->disconnect(); #断开数据库链接
}