使用DBD :: SQLite文档中sqlite_open_flags
说明的属性:
use DBD::SQLite; my $dbh = DBI->connect("dbi:SQLite:$dbfile", undef, undef, { sqlite_open_flags => DBD::SQLite::OPEN_READONLY, });
如果您尝试打开不存在的数据库(通常会创建新数据库)或尝试写入现有数据库,则会导致错误.
请注意,您必须明确use DBD::SQLite;
地使用常量DBD::SQLite::OPEN_READONLY
.
请注意,DBI提供了ReadOnly
handle属性,但DBD :: SQLite在v1.49_05之前不支持它:
use strict; use warnings; use Data::Dump; use DBI; my $db = 'foo.db'; unlink $db if -f $db; my $dbh = DBI->connect("dbi:SQLite:dbname=$db",'','', { RaiseError => 1, ReadOnly => 1 }); $dbh->do( q{CREATE TABLE foo(id INTEGER, name TEXT)} ); $dbh->do( q{INSERT INTO foo VALUES(1, 'foo')} ); my $values = $dbh->selectall_arrayref( q{SELECT * FROM foo} ); dd $values;
输出:
[[1, "foo"]]
切换到sqlite_open_flags => DBD::SQLite::OPEN_READONLY
会导致错误.
如果数据库不存在:
DBI connect('dbname=foo.db','',...) failed: unable to open database file
如果数据库存在:
DBD::SQLite::db do failed: attempt to write a readonly database
从DBD :: SQLite v1.49_05开始,您也可以使用该ReadOnly
属性,但仅作为选项使用connect
.连接后设置属性不起作用并抛出警告:
my $dbh = DBI->connect("dbi:SQLite:dbname=$db",'','', { RaiseError => 1 }); $dbh->{ReadOnly} = 1;
输出:
DBD :: SQLite :: db STORE警告:ReadOnly已设置,但它只是建议