Introduction to open source embedded database SQLite

 

  Description: Since decades ago commercial applications emerge, the database will become a major component of the software application. Like being critical database management systems, they become very large, and take up a considerable amount of system resources, increases the complexity of management. With the modular software applications gradually, a new database will be better suited than the traditional large and complex database management systems. Embedded database runs directly in the application process, provides zero-configuration (zero-configuration) mode of operation, and resource consumption is very small. This article will introduce the popular SQLite database engine, and describes how to use it in application development.

  D. Richard Hipp SQLite is written in C, open source embedded database engine. It is completely independent, having no external dependencies. It is as an option introduced in PHP V4.3, built in PHP V5. SQLite supports most SQL92 standards, runs on all major operating systems and supports most computer languages. SQLite also very robust. Its creator is conservatively estimated to SQLite can handle up to 100,00 times daily burden hits the Web site, and sometimes SQLite can handle 10 times the load in the above figures.

Features

  SQLite support for SQL92 standards include indexes, constraints, triggers and view. SQLite does not support foreign key constraints, but support for atomic, consistent, independent and durable (ACID) transactions (the back will provide more information about the ACID).

Why embedding?

  Embedded database name from its unique mode of operation. This database is embedded into the application process, eliminating the overhead associated with a client-server configuration. Embedded database is actually lightweight, at run time, they require less memory. They are using thin code written for embedded devices, it is faster, the effect is more ideal. Embedded operating mode allows the embedded database to easily manage application data via SQL, rather than relying on the original text file. Embedded database also provides zero-configuration mode of operation, so that one can be enabled and run a snapshot.

  You know, SQLite database permissions only depends on the file system, there is no concept of user accounts. There SQLite database-level locking, no network server, and can achieve most of SQL92 standard (but not all). Other major features SQL92 standard is a foreign key and check constraints. Learn what SQL92 function is not implemented.

  This means that transactions are atoms , because they are either fully executed or not at all. The transaction is consistent , because in an inconsistent state, the database has never been reserved. Transaction or independent , so if there are two transactions to perform an operation on the same database at the same time, the two transactions are non-interfering. And the transaction is persistent , so that the database can survive the crash and power failure without loss of data or damage.

  SQLite transaction processing to achieve independence through exclusive and shared on a database-level locking. This means that when multiple processes and threads can read data from the same database at the same time, but only one can write data. Before performing the write operation to the database of a process or thread, you must obtain an exclusive lock. After issuing exclusive lock, others read or write operation will not happen again.

  A complete record on the SQLite site SQLite locking semantics .


Internal structure

  Internally, SQLite consists of the following components: SQL compiler, kernel, and the rear end attachment. SQLite through the use of virtual machines and virtual database engine (VDBE), the debug, modify and extend SQLite kernel easier. All SQL statements are compiled into easy to read, the assembly can be performed in the SQLite virtual machine.

  An internal configuration of FIG. 1. SQLite

  SQLite support up to 2 TB size of the database, each database is stored completely in a single disk file. These disk files may be moved between a computer of different byte order. These data are stored in B + trees (B + Tree) data structure on the disk. SQLite database to obtain its permission based on the file system.

type of data

  SQLite does not support static data type, but the use of columns relations. This means that its data type does not have a listed property, and has the attribute data itself. When a value into the database, SQLite checks its type. If the type of associated columns do not match, then the SQLite attempts to convert the value to the column type. If not converted, then the value of the type as having its own memory.

  SQLite support NULL, INTEGER, REAL, TEXTand BLOBdata types.


SQLite Management

  SQLite comes with a download of the Command-Line interface for Database Administration . This program can be invoked through the command-line database name, and you can create new databases and tables in the following manner:

Listing 1. Create a new database and table
C:\minblogg>sqlite3 c:\minblogg\www\db\alf.db
SQLite version 3.2.1
Enter ".help" for instructions
sqlite> create table mytable(name varchar(40), age smallint);
sqlite> insert into mytable values('Nils-Erik',23);
sqlite> select * from mytable;
Nils-Erik|23
sqlite>

  You can then open the database again, it lists the tables and architecture, and proceed to insert and delete values.

Listing 2. Listing tables and architecture
 
C:\minblogg>sqlite3 c:\minblogg\www\db\alf.db
SQLite version 3.2.1
Enter ".help" for instructions
sqlite> .tables
mytable
sqlite> select * from mytable;
Nils-Erik|23
sqlite> .schema
CREATE TABLE mytable(name varchar(40), age smallint);
sqlite>

  SQLite also comes with command-line database analyzer that allows you to display detailed information about the current status of any SQLite database.

Listing 3. SQLite Analyzer
 
C:\minblogg>sqlite3_analyzer www\db\alf.db
Analyzing table mytable...
Analyzing table sqlite_master...
/** Disk-Space Utilization Report For www\db\alf.db
*** As of 2005-Apr-24 18:56:40
Page size in bytes.................... 1024
Pages in the whole file (measured).... 2
Pages in the whole file (calculated).. 2
Pages that store data................. 2          100.0%
Pages on the freelist (per header).... 0            0.0%
Pages on the freelist (calculated).... 0            0.0%
Pages of auto-vacuum overhead......... 0            0.0%
Number of tables in the database...... 2
Number of indices..................... 0
Number of named indices............... 0
Automatically generated indices....... 0
Size of the file in bytes............. 2048
Bytes of user payload stored.......... 13           0.63%
*** Page counts for all tables with their indices ********************
MYTABLE............................... 1           50.0%
SQLITE_MASTER......................... 1           50.0%
*** All tables *******************************************************
Percentage of total database.......... 100.0%
Number of entries..................... 2
Bytes of storage consumed............. 2048
Bytes of payload...................... 91           4.4%
Average payload per entry............. 45.50
Average unused bytes per entry........ 916.50
Maximum payload per entry............. 78
Entries that use overflow............. 0            0.0%
Primary pages used.................... 2
Overflow pages used................... 0
Total pages used...................... 2
Unused bytes on primary pages......... 1833        89.5%
Unused bytes on overflow pages........ 0
Unused bytes on all pages............. 1833        89.5%
*** Table MYTABLE ****************************************************
Percentage of total database..........  50.0%
Number of entries..................... 1
Bytes of storage consumed............. 1024
Bytes of payload...................... 13           1.3%
Average payload per entry............. 13.00
Average unused bytes per entry........ 999.00
Maximum payload per entry............. 13
Entries that use overflow............. 0            0.0%
Primary pages used.................... 1
Overflow pages used................... 0
Total pages used...................... 1
Unused bytes on primary pages......... 999         97.6%
Unused bytes on overflow pages........ 0
Unused bytes on all pages............. 999         97.6%

  Because fully able to use the command line interface to manage the database, so it can bring great convenience for the database administrator. There are many excellent Web-based SQLite database management systems. There is a PHP-based SQLiteManager .


Backup

  SQLite database backup in two ways. If the database is in use, you should use the command line interface .dump command. This will create a file containing the necessary commands and data in order to re-create the database. .dumpCommand can also be used to back up the database tables.

Listing 4. .dumpCommand
 
sqlite> .dump
BEGIN TRANSACTION;
CREATE TABLE mytable(name varchar(40), age smallint);
INSERT INTO "mytable" VALUES('Nils-Erik', 23);
COMMIT;
sqlite>

  如果数据库没有处于使用状态,则可以直接将数据库文件复制到安全位置。


在 PHP V5 中使用 SQLite

  一个好的做法是将 SQLite 数据库与 PHP 代码分开。完成此操作的一个简便方法是创建一个 www 目录。在此目录中,创建一个用于存放 SQLite 数据库的 db 目录、一个用于存放数据库和表创建脚本的 dbscripts 目录和一个用于存放数据库备份的 backups 目录。

清单 5. 使用 PHP V5 组织 SQLite 数据库
2004-12-06  15:43    DIR          .
2004-12-06  15:43    DIR          ..
2005-04-23  19:55    DIR          db
2005-01-02  11:46    DIR          dbscripts
2005-01-02  11:46    DIR          backups

  在 PHP V5 中创建 SQLite 数据库与在命令行界面中创建该数据库非常相似。如果该数据库不存在,则创建一个空数据库。

$db = sqlite_open('../db/ac.db');

  创建一个表也非常容易:

清单 6. 创建表
$db = sqlite_open('../db/ac.db');
sqlite_query($db, 'DROP TABLE post');
sqlite_query($db, 'CREATE TABLE post (id INTEGER PRIMARY KEY, 
   kategori VARCHAR(20) NOT NULL, 
titel VARCHAR(75) NOT NULL, referens VARCHAR(75), status VARCHAR(20) not null, 
date varchar(10)not null, synopsis VARCHAR(120), inlaegg varchar(8192))');

  插入一条记录:

$sqldb = sqlite_open("../db/ac.db");
sqlite_query($sqldb, "INSERT INTO isvs VALUES ('$isvurl' , '$isvname', '$comment')");

  并选择数据:

清单 7. 从 SQLite 数据库中选择数据
$sqldb = sqlite_open("www/db/ac.db");
$results = sqlite_query($sqldb, "SELECT * FROM isvs order by isvurl asc ");
   
while (list($isvurl, $isvname) = sqlite_fetch_array($results)) {
  sqlite_close($sqldb);

使用 SQLite 和数据库抽象层

  两个先进的开源数据库抽象层对 SQLite 提供支持:PEAR::DB,它们包含在 PHP V5 中,并且被认为是更轻量级的 ezSQL。通过预先使用 PHP 扩展和应用程序库 (PEAR) 或 ezSQL,可将 SQLite 用于应用程序的快速复原,在以后需要时,可以将其无缝转向更具工业性质的数据库。

清单 8. 使用 ezSQL 和 SQLite
$users = $db->get_results("SELECT name, age FROM table1");
foreach ( $users as $user )
{
            echo $user->name;
            echo $user->age;
}

城中另一个游戏

  SQLite 不是惟一的开源嵌入式数据库引擎。如果 SQLite 不能满足您的要求,请使用 Derby(是 Apache 孵化器项目)和 Cloudscape(IBM 公司的 Derby 商业版本,包括 IBM 支持和服务)。Cloudscape 于 1996 年诞生于 Cloudscape 公司。三年以后,Informix 软件公司并购了 Cloudscape,2001 年,IBM 并购了 Informix 软件公司的数据库资产,其中包括 Cloudscape。去年,IBM 将此代码像 “Derby”一样作为孵化器项目献给了 Apache Software Foundation。

  Derby 是100% 的 Java 编程语言关系数据库,并提供了存储过程和触发器,行级锁定,可以执行事务提交和回退操作,并支持加密。

  最近,Zend 公司为 IBM 发布了 Zend Core,该软件可以看作是基于 PHP V5 的解决方案,其中包括用于 Cloudscape 的 PHP 扩展和绑定的 Cloudscape 数据库服务器。


SQLite 使用注意事项

  在确定是否在应用程序中使用 SQLite 之前,应该考虑以下几种情况:

  • 目前没有可用于 SQLite 的网络服务器。从应用程序运行位于其他计算机上的 SQLite 的惟一方法是从网络共享运行。这样会导致一些问题,像 UNIX® 和 Windows® 网络共享都存在文件锁定问题。还有由于与访问网络共享相关的延迟而带来的性能下降问题。
  • SQLite 只提供数据库级的锁定。虽然有一些增加并发的技巧,但是,如果应用程序需要的是表级别或行级别的锁定,那么 DBMS 能够更好地满足您的需求。
  • 正如前面提到的,SQLite 可以支持每天大约 100,00 次点击率的 Web 站点 —— 并且,在某些情况下,可以处理 10 倍于此的通信量。对于具有高通信量或需要支持庞大浏览人数的 Web 站点来说,应该考虑使用 DBMS。
  • SQLite 没有用户帐户概念,而是根据文件系统确定所有数据库的权限。这会使强制执行存储配额发生困难,强制执行用户许可变得不可能。
  • SQLite 支持多数(但不是全部)的 SQL92 标准。不受支持的一些功能包括完全触发器支持和可写视图。请参阅 unimplemented SQL92 features

  如果您感到其中的任何限制会影响您的应用程序,那么您应该考虑使用完善的 DBMS。如果您可以解除这些限制问题,并且对快速灵活的嵌入式开源数据库引擎很感兴趣,则应重点考虑使用 SQLite。

  一些能够真正表现 SQLite 优越性能的领域是 Web 站点,可以使用 SQLite 管理应用程序数据、快速应用程序原型制造和培训工具。


结束语

  由于资源占用少、性能良好和零管理成本,嵌入式数据库有了它的用武之地,它将为那些以前无法提供用作持久数据的后端的数据库的应用程序提供了高效的性能。现在,没有必要使用文本文件来实现持久存储。SQLite 之类的嵌入式数据库的易于使用性可以加快应用程序的开发,并使得小型应用程序能够完全支持复杂的 SQL。这一点对于对于小型设备空间的应用程序来说尤其重要。

  嵌入式数据库对于加快应用程序开发也很重要,尤其是在用于数据库抽象层(例如 PEAR::DBezSQL)时。最后,SQLite 正在积极开发中,未来一定会有新的功能,会对开源社区更有用。

参考资料

  • 您可以参阅本文在 developerWorks 全球站点上的 英文原文
  • 请访问 SQLite,以下载最新版本的 SQLite、命令行界面、文档和最新消息。
  • 下载 SQLiteManager,使 SQLite 数据库管理更方便。
  • PHP.net下载包括 SQLite 的 PHP V5。
  • 请参阅 developerWorks 上的文章“ 审计 PHP,第 1 部分: 理解 register_globals”,了解开发人员创建 PHP 应用程序时需要牢记的一些基本问题。
  • PHP 简介”是对 PHP 脚本语言的一个简要介绍,并讨论了 PHP 的起源、功能及其使用的平台。
  • PHP 例解,第 1 部分”是系列文章中第一部分,它介绍了 PHP 的一些基础知识。描述了包括作者页和前端的 Webzine,在作者页中,内容提供者可以输入文章的正文,前端用于将这些内容介绍给全世界的读者。
  • 学习 PHP,第 1 部分” 是由三个部分组成的文章列系中的第 1 部分,通过记录文档工作流系统的构建过程,全面介绍 PHP,从文件系统的最基本的 PHP 脚本,到使用数据库和流。
  • 可以从 The PHP Extension and Application Repository获得 PEAR::DB 数据库抽象层。
  • 请访问 jvmultimedia,下载 ezSQL 数据库抽象层。
  • 请购买 Chris Newman 撰写的 SQLite 一书,该书主要介绍了开源的嵌入式数据库。
  • 了解关于 Apache 孵化项目 DerbyIBM Cloudscape的更多信息。
  • 请下载包括 Cloudscape 的 combined PHP V5 binary distribution
  • 请参阅 developerWorks 的 开源专区,了解更多的 how-to 信息、工具和项目更新,帮助您使用开源技术进行开发,并将这些技术用于 IBM 的产品中。
  • 使用 IBM 试用软件改进您的下一个开源开发项目,可以通过下载或从 DVD 中获得这些软件。
  • 通过参与 developerWorks blogs 加入 developerWorks 社区。

关于作者

  Nils-Erik Frantzell 是一名位于圣克鲁斯的加州大学的大学四年级学生。他的兴趣包括数据库(尤其是内部数据库)、信息管理、Web 技术以及一些计算机硬件。他的业余爱好是饲养热带鱼和欣赏电子音乐。

 

本文转自:http://www.ibm.com/developerworks/cn/opensource/os-sqlite/

转载于:https://www.cnblogs.com/renzo/archive/2012/01/07/2315399.html

Guess you like

Origin blog.csdn.net/weixin_34161029/article/details/94250105