SQLite 与 Perl 的使用
                           
天天向上
发布: 2025-03-05 23:14:24

原创
195 人浏览过

SQLite 是一个轻量级的嵌入式数据库,适用于小型应用、脚本和测试环境。Perl 提供了 DBI(数据库接口模块)和 DBD::SQLite(SQLite 驱动),可以方便地操作 SQLite 数据库。


1. 安装 SQLite 模块

在使用 SQLite 之前,需要安装 DBIDBD::SQLite 模块:

cpan DBI
cpan DBD::SQLite

或者使用 cpanm(推荐):

cpanm DBI
cpanm DBD::SQLite

如果你使用的是 Debian/Ubuntu:

sudo apt-get install libdbd-sqlite3-perl

2. 连接 SQLite 数据库

使用 DBI->connect 连接 SQLite 数据库:

use strict;
use warnings;
use DBI;

my $db_file = "test.db";
my $dbh = DBI->connect("dbi:SQLite:dbname=$db_file","","", { RaiseError => 1, AutoCommit => 1 })
    or die $DBI::errstr;

print "成功连接 SQLite 数据库\n";

如果 test.db 文件不存在,SQLite 会自动创建它。


3. 创建表

my $sql = qq{
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER NOT NULL
    );
};
$dbh->do($sql);
print "表创建成功\n";

4. 插入数据

my $sth = $dbh->prepare("INSERT INTO users (name, age) VALUES (?, ?)");
$sth->execute("Alice", 25);
$sth->execute("Bob", 30);
$sth->finish();
print "数据插入成功\n";

5. 查询数据

my $sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();

while (my @row = $sth->fetchrow_array) {
    print "ID: $row[0] - 姓名: $row[1] - 年龄: $row[2]\n";
}

$sth->finish();

6. 更新数据

my $sth = $dbh->prepare("UPDATE users SET age = ? WHERE name = ?");
$sth->execute(28, "Alice");
print "数据更新成功\n";

7. 删除数据

my $sth = $dbh->prepare("DELETE FROM users WHERE name = ?");
$sth->execute("Bob");
print "数据删除成功\n";

8. 使用事务

eval {
    $dbh->begin_work;
    $dbh->do("INSERT INTO users (name, age) VALUES ('Eve', 22)");
    $dbh->do("INSERT INTO users (name, age) VALUES ('David', 35)");
    $dbh->commit;
    print "事务提交成功\n";
};
if ($@) {
    $dbh->rollback;
    print "事务回滚: $@\n";
}

9. 关闭数据库连接

$dbh->disconnect();
print "数据库连接已关闭\n";

10. 其他 SQLite 高级用法

10.1. 创建索引

$dbh->do("CREATE INDEX idx_name ON users(name)");
print "索引创建成功\n";

10.2. 启用 WAL 模式

$dbh->do("PRAGMA journal_mode=WAL;");
print "WAL 模式启用\n";

10.3. 只读模式

my $dbh_ro = DBI->connect("dbi:SQLite:dbname=test.db","","", { ReadOnly => 1 });
print "数据库只读模式\n";

总结

操作SQL 语句Perl 代码
连接数据库dbi:SQLite:dbname=test.dbDBI->connect(...)
创建表CREATE TABLE ...$dbh->do(...)
插入数据INSERT INTO users (name, age) VALUES (?, ?)$sth->execute(...)
查询数据SELECT * FROM users$sth->fetchrow_array
更新数据UPDATE users SET age = ? WHERE name = ?$sth->execute(...)
删除数据DELETE FROM users WHERE name = ?$sth->execute(...)
事务BEGIN TRANSACTION$dbh->begin_work

SQLite 适用于小型项目,而 Perl 通过 DBI 让操作 SQLite 变得简单直观。如果你需要更强的数据库管理功能,可以考虑使用 MySQL 或 PostgreSQL。

更多详细内容请关注其他相关文章。

发表回复 0

Your email address will not be published. Required fields are marked *