在Perl中使用SQLite数据库也是相对简单的。以下是一个简单的例子,演示如何连接到SQLite数据库、创建表格、插入数据以及查询数据。

1. 安装 DBI 和 DBD::SQLite 模块:

   在 Perl 中使用 SQLite,首先需要确保你安装了 DBI(Database Interface)和 DBD::SQLite(SQLite driver for DBI)模块。你可以使用 cpan 工具来安装它们:
   cpan DBI
   cpan DBD::SQLite

2. 连接到SQLite数据库:

   创建一个 Perl 脚本,连接到 SQLite 数据库:
   use strict;
   use warnings;
   use DBI;

   # 连接到SQLite数据库
   my $dbfile = "your_database.db";
   my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","",{RaiseError => 1}) or die $DBI::errstr;

   print "Connected to the database\n";

   # 在这里添加数据库操作代码

   # 关闭数据库连接
   $dbh->disconnect();

   请替换 "your_database.db" 为你实际的数据库文件路径。

3. 创建表格和插入数据:

   使用 $dbh->do 方法执行 SQL 语句创建表格并插入数据:
   use strict;
   use warnings;
   use DBI;

   # 连接到SQLite数据库
   my $dbfile = "your_database.db";
   my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","",{RaiseError => 1}) or die $DBI::errstr;

   # 创建users表格
   $dbh->do('
       CREATE TABLE IF NOT EXISTS users (
           id INTEGER PRIMARY KEY AUTOINCREMENT,
           username TEXT NOT NULL,
           password TEXT NOT NULL
       )
   ');

   # 插入数据
   $dbh->do("INSERT INTO users (username, password) VALUES ('john_doe', 'password123')");

   # 关闭数据库连接
   $dbh->disconnect();

   请替换 "your_database.db" 为你实际的数据库文件路径。

4. 查询数据:

   查询数据的例子如下:
   use strict;
   use warnings;
   use DBI;

   # 连接到SQLite数据库
   my $dbfile = "your_database.db";
   my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","",{RaiseError => 1}) or die $DBI::errstr;

   # 查询数据
   my $sth = $dbh->prepare('SELECT * FROM users');
   $sth->execute();

   while (my $row = $sth->fetchrow_hashref()) {
       print "ID: $row->{id}, Username: $row->{username}, Password: $row->{password}\n";
   }

   # 关闭数据库连接
   $dbh->disconnect();

   请替换 "your_database.db" 为你实际的数据库文件路径。

确保你有适当的权限来读写数据库文件。使用 Perl 的 DBI 模块,你可以执行各种数据库操作,并以安全的方式执行查询,以避免 SQL 注入攻击。


转载请注明出处:http://www.zyzy.cn/article/detail/14206/SQLite