DBD::SQLite โ Self-contained RDBMS in a DBI Driver
| Use Case | Command | Description |
|---|---|---|
| ๐ Connect to file DB | DBI->connect("dbi:SQLite:dbname=$file","","") | Opens/creates a file-based SQLite database |
| ๐ง In-memory DB | DBI->connect("dbi:SQLite::memory:","","") | Temporary in-memory database for testing |
| ๐ Enable foreign keys | $dbh->do("PRAGMA foreign_keys = ON") | Enforce foreign key constraints |
| โฑ๏ธ Busy timeout | $dbh->sqlite_busy_timeout(5000) | Wait up to 5 seconds when DB is locked |
| โก Performance | $dbh->do("PRAGMA synchronous = OFF") | Faster writes, slight corruption risk |
| ๐ WAL mode | $dbh->do("PRAGMA journal_mode = WAL") | Write-ahead logging for concurrency |
| ๐ง Custom function | $dbh->sqlite_create_function('now',0,sub{time}) | Register a Perl function for use in SQL |
| ๐พ Backup to file | $dbh->sqlite_backup_to_file($filename) | Backup current DB to a file |
| ๐ฅ Backup from file | $dbh->sqlite_backup_from_file($filename) | Restore DB from a backup file |
| ๐ Load extension | $dbh->sqlite_load_extension($file) | Load an external SQLite extension |
| ๐ข Last insert ID | $dbh->last_insert_id("","","","") | Retrieve the last inserted rowid |
| ๐ Cache size | $dbh->do("PRAGMA cache_size = 800000") | Set DB cache to ~800MB |
| ๐ Read-only open | connect(...,{sqlite_open_flags=>SQLITE_OPEN_READONLY}) | Open database in read-only mode |
| ๐ Unicode mode | $dbh->{sqlite_string_mode}=DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK | Proper Unicode handling |
| ๐ Multiple statements | connect(...,{sqlite_allow_multiple_statements=>1}) | Execute SQL dumps via do() |
use DBI;
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
SQLite is a public domain file-based relational database engine that you can find at <https://www.sqlite.org/>.
DBD::SQLite is a Perl DBI driver for SQLite, that includes the entire thing in the distribution. So in order to get a fast transaction capable RDBMS working for your perl project you simply have to install this module, and nothing else.
SQLite supports the following features:
DBD::SQLite is usually compiled with a bundled SQLite library (SQLite version 3.36.0 as of this release) for consistency. You can check:
$DBD::SQLite::sqlite_version # "3.x.y"
$DBD::SQLite::sqlite_version_number # "3xxxyyy"
DBD::SQLite::Constants::SQLITE_VERSION_NUMBER()
You can also check compile options via DBD::SQLite::compile_options().
SQLite creates a file per database. Pass the path in the DBI connection string:
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
The file is opened in read/write mode and created if it doesn't exist. The directory must be writable (SQLite creates temp files there).
:memory: โ private, temporary in-memory database; vanishes on disconnectmy $dbh = DBI->connect("dbi:SQLite:uri=file:$path_to_dbfile?mode=rwc");
Note: URIs are for local databases only, not remote connections.
use DBD::SQLite::Constants qw/:file_open/;
my $dbh = DBI->connect("dbi:SQLite:$dbfile", undef, undef, {
sqlite_open_flags => SQLITE_OPEN_READONLY,
});
As of 1.49_05, you can also set ReadOnly attribute to true at connect time.
EXLOCK => 0 to avoid "database is locked" errors.($fh, $filename) = tempfile($template, EXLOCK => 0);
๐ก Tip: For temporary databases, prefer :memory: โ it's cleaner for testing.
โ ๏ธ Under Unix, do not carry an open SQLite database across a fork() call. Re-open the database after forking. Consider tweaking sqlite_busy_timeout and sqlite_use_immediate_transaction for forked environments.
dbish dbi:SQLite:foo.db
Or install the standalone sqlite3 command line tool from sqlite.org.
As of v1.11, blobs "just work" as text columns. For native BLOB storage, use SQL_BLOB:
use DBI qw(:sql_types);
my $blob = `cat foo.jpg`;
my $sth = $dbh->prepare("INSERT INTO mytable VALUES (1, ?)");
$sth->bind_param(1, $blob, SQL_BLOB);
$sth->execute();
Retrieval works normally via fetch.
โ ๏ธ By default, DBD::SQLite treats all bind values as text (quoted). This causes issues with numeric comparisons. Four workarounds:
bind_param() explicitly:use DBI qw(:sql_types);
$sth->bind_param(1, 5, SQL_INTEGER);
count(*) > (? + 0)cast(): count(*) > cast(? as integer)sqlite_see_if_its_a_number: (easiest, but may cause issues with existing text-as-number data)$dbh->{sqlite_see_if_its_a_number} = 1;
SQLite supports ?, :AAAA, and numbered placeholders (?1, ?2). Avoid mixing ? with numbered/named placeholders.
my $sth = $dbh->prepare('update TABLE set a=?1 where b=?2 and a IS NOT ?1');
$sth->execute(1, 2);
SQLite PRAGMAs modify operation or query internal data. Key pragmas:
DELETE (default), TRUNCATE (faster), WAL (persistent write-ahead log, v3.7.0+)Supported since SQLite 3.6.19. Disabled by default. Enable immediately after connecting:
$dbh->do("PRAGMA foreign_keys = ON");
Disable with: $dbh->do("PRAGMA foreign_keys = OFF");
Behavior depends on AutoCommit:
begin_work/commit for explicit transactions. AutoCommit temporarily off during transaction.BEGIN issued automatically. Commit/rollback freely; next statement auto-starts new transaction.$dbh->{AutoCommit} = 1;
$dbh->begin_work; # or $dbh->do('BEGIN TRANSACTION')
$dbh->commit; # AutoCommit restored
$dbh->{AutoCommit} = 0;
# BEGIN issued automatically
$dbh->commit; # next statement auto-begins
$dbh->{AutoCommit} = 1; # exit transactional mode
Default SQLite transaction is "deferred" (locks acquired on first read/write). DBD::SQLite issues BEGIN IMMEDIATE by default since 1.38_01 to prevent deadlocks. To use deferred:
my $dbh = DBI->connect("dbi:SQLite::memory:", "", "", {
sqlite_use_immediate_transaction => 0,
});
โ ๏ธ SQLite prohibits ROLLBACK of unfinished SELECT statements. Call finish before rollback:
$sth = $dbh->prepare("SELECT * FROM t");
$dbh->begin_work;
eval {
$sth->execute;
$row = $sth->fetch;
die "For some reason";
};
if($@) {
$sth->finish; # REQUIRED for SQLite
$dbh->rollback;
} else {
$dbh->commit;
}
Set sqlite_allow_multiple_statements to true; then do() handles multiple statements. Use $sth->{sqlite_unprepared_statements} to retrieve leftovers from prepare.
SQLite is very fast. Tips for best performance:
PRAGMA synchronous = OFF (disables fsync, much faster writes)PRAGMA cache_size โ default 2MB; try up to 800MB for large datasets$dbh->do("PRAGMA cache_size = 800000"); # ~800MB cache
DBD_SQLITE_STRING_MODE_BYTES โ All strings are bytes (code points >255 throw exception)DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK โ UTF-8 encode/decode with warning fallbackDBD_SQLITE_STRING_MODE_UNICODE_STRICT โ Like FALLBACK but throws exceptionsDBD_SQLITE_STRING_MODE_UNICODE_NAIVE โ Faster, no validation (can corrupt Perl!)DBD_SQLITE_STRING_MODE_PV โ โ ๏ธ Default but DO NOT USE; uses Perl's internal byte buffersqlite_string_modedo()$sth = $dbh->table_info(undef, $schema, $table, $type, \%attr);
Returns tables/views. Schema and table do LIKE search. $type accepts comma-separated: 'TABLE', 'VIEW', 'LOCAL TEMPORARY', 'SYSTEM TABLE'. Returns fields: TABLE_CAT (always NULL), TABLE_SCHEM, TABLE_NAME, TABLE_TYPE.
@names = $dbh->primary_key(undef, $schema, $table);
$sth = $dbh->primary_key_info(undef, $schema, $table, \%attr);
$sth = $dbh->foreign_key_info(undef, $pk_schema, $pk_table,
undef, $fk_schema, $fk_table);
Non-empty fields: PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_NAME, FKCOLUMN_NAME, KEY_SEQ, UPDATE_RULE, DELETE_RULE, DEFERRABILITY, UNIQUE_OR_PRIMARY. โ ๏ธ Foreign key support must be enabled via PRAGMA foreign_keys = ON.
$sth = $dbh->statistics_info(undef, $schema, $table, $unique_only, $quick);
Non-empty fields: TABLE_SCHEM, TABLE_NAME, NON_UNIQUE, INDEX_NAME, TYPE ('btree'), ORDINAL_POSITION, COLUMN_NAME.
my $bool = $dbh->ping;
Returns true if database file exists (or is in-memory) and connection is active.
If using DBI >= 1.608, use the sqlite_ methods directly. For older DBI:
$dbh->func( ..., "(method name without sqlite_ prefix)" );
โ ๏ธ Exception: sqlite_trace should always be called with its full name to avoid conflict with DBI's trace().
Returns the last inserted rowid. ๐ก Prefer DBI's $h->last_insert_id($catalog, $schema, $table_name, $field_name [, \%attr]) instead. Equivalent: $h->last_insert_id("","","","").
Retrieve current (main) database filename. Returns empty string or undef for in-memory/temporary databases.
Get/set the busy timeout in milliseconds.
Register a custom SQL function. $argc = -1 means any number of arguments. $flags (optional): SQLITE_DETERMINISTIC for better performance. Return a scalar (treated as text/number), or an arrayref [value, SQL_BLOB] for typed returns.
$dbh->sqlite_create_function( 'now', 0, sub { return time } );
# Usage: INSERT INTO mytable ( now() );
# Typed return (BLOB):
$dbh->sqlite_create_function( 'md5', 1, sub { return [md5($_[0]), SQL_BLOB] } );
SQLite includes syntactic support for REGEXP but no implementation. DBD::SQLite automatically registers one using Perl regex with current locale.
SELECT * from table WHERE column REGEXP '\bA\w+'
SELECT * from table WHERE column REGEXP '(?i:\bA\w+)' # case-insensitive
โ ๏ธ Regexp matching does not use SQLite indices โ iterates over all rows.
Register a custom collation function for sorting. See COLLATION FUNCTIONS below.
Register a callback invoked when an undefined collation is requested. Callback: $code_ref->($dbh, $collation_name).
Register a custom aggregate function. The package must implement three methods: new(), step(@_), and finalize(). $flags optionally includes SQLITE_DETERMINISTIC.
package variance;
sub new { bless [], shift; }
sub step {
my ( $self, $value ) = @_;
push @$self, $value;
}
sub finalize {
my $self = $_[0];
my $n = @$self;
return undef unless $n && $n != 1;
my $mu = 0;
foreach my $v ( @$self ) { $mu += $v; }
$mu /= $n;
my $sigma = 0;
foreach my $v ( @$self ) { $sigma += ($v - $mu)**2; }
$sigma = $sigma / ($n - 1);
return $sigma;
}
$dbh->sqlite_create_aggregate( "variance", 1, 'variance' );
Usage: SELECT group_name, variance(score) FROM results GROUP BY group_name;
Invoke a handler periodically during long-running calls. Return non-zero to interrupt. Pass undef to unregister.
Callback invoked on commit. Return non-zero to convert commit to rollback. Returns previous callback ref. Pass undef to disable.
Callback invoked on rollback. Returns previous callback ref.
Callback invoked on row insert/update/delete: $code_ref->($action_code, $database, $table, $rowid). Action codes: DBD::SQLite::INSERT, DBD::SQLite::DELETE, DBD::SQLite::UPDATE.
Register an authorizer for SQL compilation. Callback: $code_ref->($action_code, $string1, $string2, $database, $trigger_or_view). Return DBD::SQLite::OK, DBD::SQLite::IGNORE, or DBD::SQLite::DENY.
Backup from a file into the current connection (handy for populating :memory:).
Backup current database to a file.
Backup from another database handle into current connection.
Backup current database into another handle.
Enable/disable loading external SQLite extensions.
$dbh->sqlite_enable_load_extension(1);
$sth = $dbh->prepare("select load_extension('libsqlitefunctions.so')")
or die "Cannot prepare: " . $dbh->errstr();
Load an extension directly. $file mandatory, $proc optional. Requires sqlite_enable_load_extension first.
Trace callback when SQL statements execute: $code_ref->($statement). See also DBI's TRACING.
โ ๏ธ Experimental. Profile callback: $code_ref->($statement, $elapsed_time) (time in ms). See also DBI::Profile.
๐ Internal use only.
Returns hashref of DB connection status (cache usage, etc.). Pass 0 to reset.
Returns hashref of statement status (full table scan count, etc.). Pass 0 to reset.
my $status = $sth->sqlite_st_status();
my $cur = $status->{fullscan_step};
Configure database behavior. Pass negative value to query without changing.
use DBD::SQLite::Constants qw/:database_connection_configuration_options/;
$dbh->sqlite_db_config( SQLITE_DBCONFIG_DEFENSIVE, 1 );
$dbh->sqlite_db_config( SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 0 );
my $current = $dbh->sqlite_db_config( SQLITE_DBCONFIG_DEFENSIVE, -1 );
Register a virtual table module. See DBD::SQLite::VirtualTable.
Set/get run-time limits. Category IDs from DBD::SQLite::Constants. Negative value = query only.
Returns true if internal SQLite connection is in autocommit mode. May differ from $dbh->{AutoCommit}.
Returns internal SQLite transaction state: SQLITE_TXN_NONE, SQLITE_TXN_READ, SQLITE_TXN_WRITE. Returns -1 if unsupported or bad schema name.
my $status = DBD::SQLite::sqlite_status();
my $cur = $status->{memory_used}{current};
my $high = $status->{memory_used}{highwater};
Available when you use DBD::SQLite; at compile time. See <https://www.sqlite.org/c3ref/constlist.html>.
DBD::SQLite::OK
DBD::SQLite::DENY
DBD::SQLite::IGNORE
Used with sqlite_set_authorizer. Each has associated string1 and string2:
# constant string1 string2
CREATE_INDEX Index Name Table Name
CREATE_TABLE Table Name undef
CREATE_TEMP_INDEX Index Name Table Name
CREATE_TEMP_TABLE Table Name undef
CREATE_TEMP_TRIGGER Trigger Name Table Name
CREATE_TEMP_VIEW View Name undef
CREATE_TRIGGER Trigger Name Table Name
CREATE_VIEW View Name undef
DELETE Table Name undef
DROP_INDEX Index Name Table Name
DROP_TABLE Table Name undef
DROP_TEMP_INDEX Index Name Table Name
DROP_TEMP_TABLE Table Name undef
DROP_TEMP_TRIGGER Trigger Name Table Name
DROP_TEMP_VIEW View Name undef
DROP_TRIGGER Trigger Name Table Name
DROP_VIEW View Name undef
INSERT Table Name undef
PRAGMA Pragma Name 1st arg or undef
READ Table Name Column Name
SELECT undef undef
TRANSACTION Operation undef
UPDATE Table Name Column Name
ATTACH Filename undef
DETACH Database Name undef
ALTER_TABLE Database Name Table Name
REINDEX Index Name undef
ANALYZE Table Name undef
CREATE_VTABLE Table Name Module Name
DROP_VTABLE Table Name Module Name
FUNCTION undef Function Name
SAVEPOINT Operation Savepoint Name
Example authorizer forbidding DELETE:
use DBD::SQLite;
$dbh->sqlite_set_authorizer(sub {
my $action_code = shift;
return $action_code == DBD::SQLite::DELETE ? DBD::SQLite::DENY
: DBD::SQLite::OK;
});
SQLite v3 supports user-defined collation sequences for comparing text values. See <https://www.sqlite.org/datatype3.html#collation>.
cmp operatorcmp with use localeCREATE TABLE foo(
txt1 COLLATE perl,
txt2 COLLATE perllocale,
txt3 COLLATE nocase
);
SELECT * FROM foo ORDER BY name COLLATE perllocale;
Set sqlite_unicode at connect time for proper UTF-8 flagging in collation functions:
my $dbh = DBI->connect(
"dbi:SQLite:dbname=foo", "", "",
{
RaiseError => 1,
sqlite_unicode => 1,
}
);
Use the %DBD::SQLite::COLLATION hash for on-demand loading. โ ๏ธ The hash is write-only โ new entries only; overwriting/deleting raises an exception.
use DBD::SQLite;
$DBD::SQLite::COLLATION{no_accents} = sub {
my ( $a, $b ) = map lc, @_;
tr[ร รกรขรฃรครฅรงรจรฉรชรซรฌรญรฎรฏรฑรฒรณรดรตรถรนรบรปรผรฝ]
[aaaaaacdeeeeiiiinoooooouuuuy] for $a, $b;
$a cmp $b;
};
my $sql = "SELECT ... FROM ... ORDER BY ... COLLATE no_accents";
SQLite bundles an extension for full-text indexing (FTS). See DBD::SQLite::Fulltext_search for details.
The RTREE extension enables range/multidimensional queries โ ideal for geospatial data:
CREATE VIRTUAL TABLE city_buildings USING rtree(
id, -- Integer primary key
minLong, maxLong, -- Minimum and maximum longitude
minLat, maxLat -- Minimum and maximum latitude
);
Query for containment or overlap:
# IDs contained within query coordinates
SELECT id FROM city_buildings
WHERE minLong >= ? AND maxLong <= ?
AND minLat >= ? AND maxLat <= ?
# IDs overlapping query coordinates
SELECT id FROM city_buildings
WHERE maxLong >= ? AND minLong <= ?
AND maxLat >= ? AND minLat <= ?
See <https://www.sqlite.org/rtree.html>. Custom R-Tree callbacks not yet implemented.
See DBD::SQLite::VirtualTable. Bundled virtual tables:
Retrieve bundled SQLite C source/header (since 1.30_01):
use File::ShareDir 'dist_dir';
use File::Spec::Functions 'catfile';
my $sqlite3_h = catfile(dist_dir('DBD-SQLite'), 'sqlite3.h');
# Extract specific header from amalgamated sqlite3.c:
my $what_i_want = 'parse.h';
my $sqlite3_c = catfile(dist_dir('DBD-SQLite'), 'sqlite3.c');
open my $fh, '<', $sqlite3_c or die $!;
my $code = do { local $/; <$fh> };
my ($parse_h) = $code =~ m{(
/\*+[ ]Begin[ ]file[ ]$what_i_want[ ]\*+
.+?
/\*+[ ]End[ ]of[ ]$what_i_want[ ]\*+/
)}sx;
Add DBD::SQLite to your CONFIGURE_REQUIRES to ensure consistent C sources.
sqlite2_blob_open/sqlite2_blob_close๐ Report bugs to GitHub: <https://github.com/DBD-SQLite/DBD-SQLite/issues> or RT: <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=DBD-SQLite>
๐ Master repository: <https://github.com/DBD-SQLite/DBD-SQLite>
๐ง Mailing list: <http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/dbd-sqlite>
โ ๏ธ Bugs in bundled sqlite3.[ch] should be reported to SQLite developers at sqlite.org.
Matt Sergeant <matt AT sergeant.org>, Francis J. Lacoste <flacoste AT logreport.org>, Wolfgang Sourdeau <wolfgang AT logreport.org>, Adam Kennedy <adamk AT cpan.org>, Max Maischein <corion AT cpan.org>, Laurent Dami <dami AT cpan.org>, Kenichi Ishigaki <ishigaki AT cpan.org>
The bundled SQLite code is Public Domain.
DBD::SQLite is copyright 2002โ2007 Matt Sergeant. Some parts copyright 2008 Francis J. Lacoste, 2008 Wolfgang Sourdeau, 2008โ2013 Adam Kennedy, 2009โ2013 Kenichi Ishigaki. Some parts derived from DBD::SQLite::Amalgamation copyright 2008 Audrey Tang.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-08 09:33 @216.73.216.248
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format