⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqlite.pm

📁 Astercon2 开源软交换 2.2.0
💻 PM
📖 第 1 页 / 共 2 页
字号:
in order to get a fast transaction capable RDBMS working for yourperl project you simply have to install this module, and B<nothing>else.SQLite supports the following features:=over 4=item Implements a large subset of SQL92See http://www.hwaci.com/sw/sqlite/lang.html for details.=item A complete DB in a single disk fileEverything for your database is stored in a single disk file, making iteasier to move things around than with DBD::CSV.=item Atomic commit and rollbackYes, DBD::SQLite is small and light, but it supports full transactions!=item ExtensibleUser-defined aggregate or regular functions can be registered with theSQL parser.=backThere's lots more to it, so please refer to the docs on the SQLite webpage, listed above, for SQL details. Also refer to L<DBI> for detailson how to use DBI itself.=head1 CONFORMANCE WITH DBI SPECIFICATIONThe API works like every DBI module does. Please see L<DBI> for moredetails about core features.Currently many statement attributes are not implemented or arelimited by the typeless nature of the SQLite database.=head1 DRIVER PRIVATE ATTRIBUTES=head2 Database Handle Attributes=over 4=item sqlite_versionReturns the version of the SQLite library which DBD::SQLite is using,e.g., "2.8.0". Can only be read.=item unicodeIf set to a true value, DBD::SQLite will turn the UTF-8 flag on for all textstrings coming out of the database. For more details on the UTF-8 flag seeL<perlunicode>. The default is for the UTF-8 flag to be turned off.Also note that due to some bizareness in SQLite's type system (seehttp://www.sqlite.org/datatype3.html), if you want to retainblob-style behavior for B<some> columns under C<< $dbh->{unicode} = 1>> (say, to store images in the database), you have to state soexplicitely using the 3-argument form of L<DBI/bind_param> when doingupdates:    use DBI qw(:sql_types);    $dbh->{unicode} = 1;    my $sth = $dbh->prepare         ("INSERT INTO mytable (blobcolumn) VALUES (?)");    $sth->bind_param(1, $binary_data, SQL_BLOB); # binary_data will    # be stored as-is.Defining the column type as BLOB in the DDL is B<not> sufficient.=back=head1 DRIVER PRIVATE METHODS=head2 $dbh->func('last_insert_rowid')This method returns the last inserted rowid. If you specify an INTEGER PRIMARYKEY as the first column in your table, that is the column that is returned.Otherwise, it is the hidden ROWID column. See the sqlite docs for details.Note: You can now use $dbh->last_insert_id() if you have a recent version ofDBI.=head2 $dbh->func( 'busy_timeout' )Retrieve the current busy timeout.=head2 $dbh->func( $ms, 'busy_timeout' )Set the current busy timeout. The timeout is in milliseconds.=head2 $dbh->func( $name, $argc, $func_ref, "create_function" )This method will register a new function which will be useable in SQLquery. The method's parameters are:=over=item $nameThe name of the function. This is the name of the function as it willbe used from SQL.=item $argcThe number of arguments taken by the function. If this number is -1,the function can take any number of arguments.=item $func_refThis should be a reference to the function's implementation.=backFor example, here is how to define a now() function which returns thecurrent number of seconds since the epoch:    $dbh->func( 'now', 0, sub { return time }, 'create_function' );After this, it could be use from SQL as:    INSERT INTO mytable ( now() );=head2 $dbh->func( $name, $argc, $pkg, 'create_aggregate' )This method will register a new aggregate function which can then usedfrom SQL. The method's parameters are:=over=item $nameThe name of the aggregate function, this is the name under which thefunction will be available from SQL.=item $argcThis is an integer which tells the SQL parser how many arguments thefunction takes. If that number is -1, the function can take any numberof arguments.=item $pkgThis is the package which implements the aggregator interface.=backThe aggregator interface consists of defining three methods:=over=item new()This method will be called once to create an object which shouldbe used to aggregate the rows in a particular group. The step() andfinalize() methods will be called upon the reference return bythe method.=item step(@_)This method will be called once for each rows in the aggregate.=item finalize()This method will be called once all rows in the aggregate wereprocessed and it should return the aggregate function's result. Whenthere is no rows in the aggregate, finalize() will be called rightafter new().=backHere is a simple aggregate function which returns the variance(example adapted from pysqlite):    package variance;    sub new { bless [], shift; }    sub step {        my ( $self, $value ) = @_;        push @$self, $value;    }    sub finalize {        my $self = $_[0];        my $n = @$self;        # Variance is NULL unless there is more than one row        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 += ($x - $mu)**2;        }        $sigma = $sigma / ($n - 1);        return $sigma;    }    $dbh->func( "variance", 1, 'variance', "create_aggregate" );The aggregate function can then be used as:    SELECT group_name, variance(score) FROM results    GROUP BY group_name;=head1 BLOBSAs of version 1.11, blobs should "just work" in SQLite as text columns. Howeverthis will cause the data to be treated as a string, so SQL statements suchas length(x) will return the length of the column as a NUL terminated string,rather than the size of the blob in bytes. In order to store natively as aBLOB use the following code:  use DBI qw(:sql_types);  my $dbh = DBI->connect("dbi:sqlite:/path/to/db");    my $blob = `cat foo.jpg`;  my $sth = $dbh->prepare("INSERT INTO mytable VALUES (1, ?)");  $sth->bind_param(1, $blob, SQL_BLOB);  $sth->execute();And then retreival just works:  $sth = $dbh->prepare("SELECT * FROM mytable WHERE id = 1");  $sth->execute();  my $row = $sth->fetch;  my $blobo = $row->[1];    # now $blobo == $blob=head1 NOTESTo access the database from the command line, try using dbish which comes withthe DBI module. Just type:  dbish dbi:SQLite:foo.dbOn the command line to access the file F<foo.db>.Alternatively you can install SQLite from the link above without conflictingwith DBD::SQLite and use the supplied C<sqlite> command line tool.=head1 PERFORMANCESQLite is fast, very fast. I recently processed my 72MB log file with it,inserting the data (400,000+ rows) by using transactions and only committingevery 1000 rows (otherwise the insertion is quite slow), and then performingqueries on the data.Queries like count(*) and avg(bytes) took fractions of a second to return,but what surprised me most of all was:  SELECT url, count(*) as count FROM access_log    GROUP BY url    ORDER BY count desc    LIMIT 20To discover the top 20 hit URLs on the site (http://axkit.org), and itreturned within 2 seconds. I'm seriously considering switching my loganalysis code to use this little speed demon!Oh yeah, and that was with no indexes on the table, on a 400MHz PIII.For best performance be sure to tune your hdparm settings if you areusing linux. Also you might want to set:  PRAGMA default_synchronous = OFFWhich will prevent sqlite from doing fsync's when writing (whichslows down non-transactional writes significantly) at the expense of somepeace of mind. Also try playing with the cache_size pragma.=head1 BUGSLikely to be many, please use http://rt.cpan.org/ for reporting bugs.=head1 AUTHORMatt Sergeant, matt@sergeant.orgPerl extension functions contributed by Francis J. Lacoste<flacoste@logreport.org> and Wolfgang Sourdeau<wolfgang@logreport.org>=head1 SEE ALSOL<DBI>.=cut

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -