Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
0 1 2 3 4 5 6 7 8 9 10 11 ⽬錄 SQLite权威指南 推荐者的话 前⾔ 第1章 SQLite介绍 第2章 ⼊⻔ 第3章 关系模型 第4章 SQL 第5章 设计和概念 第6章 核⼼C API 第7章 扩充C API 第8章 语⾔扩展 第9章 SQLite内核
Page
3
SQLite权威指南 The Definitive Guide to SQLite (内容摘要) Michael Owens Copyright . 2006 by Michael Owens 本书的⽰例代码可到http://www.apress.com下载。
Page
4
推荐者的话 最近对SQLite很感兴趣,认真学习有⼀个多⽉了。 学习时基本找不到既好⼜系统的中⽂⽂章,也买不到好的中⽂书籍, 看来SQLite在国内还是不够流⾏,这么好的东西,可惜了。 以我中等偏下的眼界,《The Definitive Guide to SQLite》是我所⻅到 的最好的“SQLite⼊⻔+⼤全”了,可惜也是英⽂的。实在找不到别的, 也只好看它了,尽管我英语很不好。 由于英语很不好,⼜因为是打字员出⾝的⼲部,所以多年来养成了⼀ 个更不好的⽑病,就是在不得不看英⽂资料时总喜欢⼀边看⼀边翻, 主要是怕下次再看时还是看不懂。看《The Definitive Guide to SQLite》时这个⽑病也没改,当然了,看的时候就是挑着看的,翻的 也只是书中的⼀⼩部分了。 ⼀般情况下看完也就看完了,很少有“下次再看”的机会,这次例外。 由于越学越觉着SQLite好玩,就想向⾝边的⼈也介绍⼀下,就“再看” 了。越看越羞愧,本来英语就差,还随看随翻,结果可想⽽知。但由 于没什么动⼒,也就⽆意再重新润⾊了,就这样吧,反正也没什么⼈ 看,估计遗害不会太⼴。 SQLite是没有版权的,但这本书却是受版权保护的,也不知我这样做 是否合法。发到⽹上也只是想做⼀个好事,响应SQLite的共享精神。 估计不会有⼈来告我吧,反正我没钱。另外,我也只翻译了书中很⼩ 的⼀部分,也许根本算不上翻译(不能乱抬⾼⾃⼰),就算是对
Page
5
SQLite和《The Definitive Guide to SQLite》⼀书的⼀个推荐吧,同 样对SQLite感兴趣但⼜看不懂我的中⽂的兄弟,强烈建议看原⽂。感 谢Richard Hipp编出这么好的程序,感谢Michael Owens写出这么好 的书。 “空转”只是我的⽹名之⼀,⽹上⽹下知之者甚少,也就是⼀起骑⻋的 ⼏个⼈知道吧。如果本⽂对您能有⼀点点帮助,也算是我对SQLite做 了⼀点贡献吧。本⽂中带有“空注”的内容是我个⼈所做的简单说明和 忏悔,与原作者⽆关(以我的翻译⽔平,估计全⽂跟原作者都没什么 关)。 接触SQLite时间不⻓,所以本⽂难免会有很多错误,不是故意误导⼤ 家,是真的⽔平低。如果有兄弟想对我提出指导,我的邮箱是: njgaoyi@yahoo.com.cn。如果我没有回信,不是因为不想回,是因为 我很少上⽹,在此先⾏谢过。 分析源程序时,发现每个SQLite源⽂件的头部都有这样⼀段话: The author disclaims copyright to this source code. In place of a legal notice, here is a blessing: May you do good and not evil. May you find forgiveness for yourself and forgive others. May you share freely, never taking more than you give. 这⼏句话我很喜欢,翻译不好,就拿原⽂出来吧,与⼤家共勉。 空转 Ver 1.00: 2009-11-07 于南京
Page
6
(如果以后有时间、兴趣,就把翻译过的内容好好修改⼀下,或者再 多翻⼀些。但愿还有以后的版本)
Page
7
前⾔ 2000年春天,当我刚开始编写SQLite时,根本没想到它会在编程社区 受到如此强烈的认可。今天,有成百万的SQLite拷⻉在默默地运⾏, 在计算机中,或在不同公司⽣产的各种各样的⼩设备中。你可能已经 在⽆意识的情况下使⽤过SQLite,在你的⼿机、MP3或机顶盒⾥可能 就有SQLite。在你的计算机⾥也可能⾄少会有⼀个SQLite的拷⻉,它 可能来⾃Apple的Mac OS X,或者在⼤多数的Linux版本中,或者在 Windows中安装某个第三⽅软件时。很多Web⽹站的后台都使⽤ SQLite,这要感谢它已经被包含为PHP5语⾔的⼀部分。SQLite也被 ⽤于很多航空电⼦设备、建模和仿真程序、⼯业控制、智能卡、决策 ⽀持包、医药信息系统等。因为没有SQLite使⽤的全⾯报告,所以, 肯定还有很多我不知道的SQLite部署。 SQLite的普及很⼤程度上应该归功于Michael Owens。Mike在The Linux Journal (June 2003)和The C/C++ Users Journal (March 2004) 上的⽂章吸引了⽆数程序员。每篇⽂章发表后,SQLite⽹站的访问量 都会显著上升。通过这本书你可以看到Mike的才华和他所做的⼤量⼯ 作,相信你不会失望。本书包含了关于SQLite所需要了解的所有内 容,你应该⼀直把它放在伸⼿可及的地⽅。 SQLite是⾃由软件。尽管我是它的架构师和代码的主要编写者,但 SQLite并不是我的程序。SQLite不属于任何⼈,也不在版权的保护范 围之内。所有曾经为SQLite项⽬贡献过代码的⼈都签署过⼀个宣誓书 将他们的贡献发布到公共域,我把这些宣誓书的原件保存在办公室的
Page
8
保险箱⾥。我还尽⼒保证在SQLite中不使⽤专利算法,这些预防措施 意味着你可以以任何形式使⽤SQLite,⽽不需要付版税、许可证费⽤ 或受到其它任何限制。 SQLite仍然在发展。但我和其他开发者都坚守它的核⼼价值。我们将 保持代码的⼩规模——核⼼库不会超过250KB。我们将保持公共API 和⽂件格式的向上兼容性。我们将继续保证SQLite是充分测试的和⽆ bug的。我们希望你总是能够将新版本的SQLite放到你⽼的程序中, 既得到它新的特性和优化,⼜不需要或仅需要很少的代码改动,且不 需要做进⼀步的调试。2004年,我们将SQLite从版本2升级到版本3时 确实没能保持向上兼容性,但从那以后,我们已经能够达到上述所有 ⽬标并准备在将来继续这样做。没有SQLite版本4的计划。 真诚希望你觉着SQLite是有⽤的,我代表SQLite的所有贡献者保证, 使⽤SQLite你会:做出美好的产品,你的产品将会是快速、稳定和易 ⽤的。寻求宽恕并宽恕他⼈。因为你已经免费地得到了SQLite,也请 你免费地给予他⼈⼀些东西作为回报。做⼀回志愿者,贡献出其它的 软件项⽬或找到其它途径来回报。 Richard Hipp Charlotte, NC April 11, 2006
Page
9
第1章 SQLite介绍 SQLite是⼀个开源的、内嵌式的关系型数据库。它最初发布于2000 年,在便携性、易⽤性、紧凑性、有效性和可靠性⽅⾯有突出的表 现。
Page
10
内嵌式数据库 SQLite是⼀个内嵌式的数据库。 数据库服务器就在你的程序中,其好处是不需要⽹络配置和管理。数 据库的服务器和客户端运⾏在同⼀个进程中。这样可以减少⽹络访问 的消耗,简化数据库管理,使你的程序部署起来更容易。所有需要你 做的都已经和你的程序⼀起编译好了。 如图1-1所⽰。⼀个Perl脚本、⼀个标准C/C++程序和⼀个使⽤PHP编 写的Apache进程都使⽤SQLite。Perl脚本导⼊DBI::SQLite模板,并通 过它来访问C API。PHP采⽤与C相似的⽅式访问C API。总之,它们 都需要访问C API。尽管它们每个进程中都有独⽴的数据库服务器, 但它们可以操作相同的数据库⽂件。SQLite利⽤操作系统功能来完成 数据的同步和加锁。
Page
11
图1-1 内嵌的主进程中的SQLite ⽬前市场上有多种为内嵌应⽤所设计的关系型数据库产品,如Sybase SQL Anywhere、InterSystems Caché、Pervasive PSQL和微软的Jet Engine。有些⼚家从他们的⼤型数据库产品翻新出内嵌式的变种,如 IBM的DB2 Everyplace、Oracle的10g和微软的SQL Server Desktop Engine。开源的数据库MySQL和Firebird都提供内嵌式的版本。在所 有这些产品中,仅有两个是完全开放源代码的且不收许可证费⽤—— Firebird和SQLite。在这两个当中,仅有⼀个是专⻔为内嵌式应⽤设计 的——SQLite。
Page
12
开发者的数据库 SQLite具有多⽅⾯的特性。它是⼀个数据库,⼀个程序库,⼀个命令 ⾏⼯具,也是⼀个学习关系型数据库的很好的⼯具。确实有很多途径 可以使⽤它——内嵌环境、⽹站、操作系统服务、脚本语⾔和应⽤程 序。对于程序员来说,SQLite就象⼀个数据传送带,提供了⼀种⽅便 的将应⽤程序绑定的数据的⽅法。就象传送带⼀样,对SQLite的使⽤ 没有终点。 除了仅仅作为⼀个存储容器,SQLite还可以作为⼀个单纯的数据处理 的⼯具。如果⼤⼩和复杂性合适,使⽤SQLite可以很容易地将应⽤程 序所使⽤的数据结构转化为表,并保存在⼀个内在数据库中。⽤此⽅ 法,你可以操作互相关联的数据,可以完成很繁重的任务⻚不必写⾃ ⼰的算法来对数据结构操作和排序。如果你是⼀个程序员,想像⼀下 在你的程序中⾃⾏完成下⾯SQL语句所代表的⼯作需要多少代码: SELECT AVG(z-y) FROM table GROUP BY x HAVING x > MIN(z) OR x < MAX(y) ORDER BY y DESC LIMIT 10 OFFSET 3; SQLite还是⼀个很好的学习程序设计的⼯具,通过它可以研究很多计 算机科学的课题。分析器、分词器、虚拟机、Btree算法、⾼整缓存、 程序体系结构,通过这些内容可以搞清楚很多计算机科学的经典概 念。SQLite的模块化、⼩型化和简易性,使你可以很容易地专⻔研究 其中的⼀个问题。
Page
13
管理员的数据库 SQLite不仅是程序员的数据库,它对系统管理员也很有⽤。它很⼩、 紧凑⽽精致,就像⼀些Unix的常⽤⼯具,如find、rsync或grep。 SQLite提供了命令⾏⼯具供⽤户交互操作。 另外,对于关系型数据库的初学者来说,SQLite是⼀个学习各种关系 相关概念的⽅便的学习⼯具。它可以很快很容易地安装在各类操作系 统中,它的数据库⽂件可以⾃由共享⻚不需要任何转换。它具有关系 型数据库的各种特⾊⽽⼜不令⼈⽣畏。它的程序和数据库⽂件仅⽤U 盘就能传递。
Page
14
SQLite 的历史 从某个⾓度来说,SQLite最初的构思是在⼀条军舰上进⾏的。SQLite 的作者D. Richard Hipp当时正在为美国海军编制⼀种使⽤在导弹驱逐 舰上的程序。那个程序最初是运⾏在Hewlett-Packard Unix (HPUX) 上,后台使⽤Informix数据库。对那个程序来说,Informix有点⼉太强 ⼤了。⼀个有经验的数据库管理员(DBA)可能需要⼀整天来对它进⾏ 安装和升级,如果没经验,这个⼯作就可能永远也做不完了。 2000年⼀⽉,Hipp开始和⼀个同事讨论关于创建⼀个简单的内嵌式 SQL数据库的想法,这个数据库将使⽤GNU DBM B-Tree library (gdbm)做后台,同时这个数据库将不需要安装和管理⽀持。后来,当 有些空闲时间时,Hipp就开始实施这项⼯作,并在2000年的⼋⽉份发 布了SQLite的1.0版。 按照原定计划,SQLite 1.0⽤gdbm来做存储管理。但后来,Hipp很快 就换成了⾃⼰的B-tree,以⽀持事务和记录按主键的存储。随着最初 的升级,SQLite在功能和⽤户数上都得到了稳步的发展。在2001年中 期,很多项⽬——开源的或商业的——都开始使⽤SQLite。在那以后 的⼏年中,开源社区的其他成员开始为他们喜欢的程序设计语⾔编写 SQLite扩展。SQLite的ODBC接⼝可以为Perl、Python、Ruby、Java 和其它主流的程序设计语⾔提供⽀持,这证明了SQLite有⼴阔的应⽤ 前景。 2004年,SQLite从版本2升级到版本3,这是⼀次⼤升级。主要⽬的是 增加内置的对UTF-8、UTF-16及⽤户定义字符集的⽀持。While 3.0 was originally slated for release in summer 2005, America Online
Page
15
provided the necessary funding to see that it was completed by July 2004. 除国际化功能外,版本3的其它新特性包括:经过修补的C API,更紧凑的数据库⽂件格式(⽐原来节省25%的空间),弱类型,⼤ ⼆进制对象(BLOB)的⽀持,64-bit的ROWID,autovacuum和改进了 的并发控制。尽管增加了这⼀系列新特性,版本3的运⾏库仍然⼩于 240K字节。Another improvement in version 3 was a good code cleanup—revisiting and rewriting, or otherwise throwing out extraneous stuff accumulated in the 2.x series. SQLite持续增⻓并始终坚持其最初的设计⽬标:简单、弹性、紧凑、 速度和彻底的易⽤。本书出版时,SQLite已经增加了CHECK约束, 下⾯就要增加外键约束,再下⾯呢?
Page
16
谁使⽤SQLite 当前,SQLite已经被多种软件和产品所使⽤。它被⽤在Apple的Mac OS X操作系统中,被⽤作其CoreData应⽤程序架构的⼀部分。它还 应⽤于Safari的Web浏览器、Mail.app的电⼦邮件程序、RSS的管理、 Apple的Aperture照⽚软件。 尽管SQLite很少做⼴告,但它还是被⽤在了多种消费类产品中。
Page
17
体系结构 SQLite拥有⼀个精致的、模块化的体系结构,并引进了⼀些独特的⽅ 法进⾏关系型数据库的管理。它由被组织在3个⼦系统中的8个独⽴的 模块组成,如图1-2所⽰。这个模型将查询过程划分为⼏个不连续的任 务,就像在流⽔线上⼯作⼀样。在体系结构栈的顶部编译查询语句, 在中部执⾏它,在底部处理操作系统的存储和接⼝。 图1-2 SQLite的体系结构
Page
18
接⼝(Interface) 接⼝由SQLite C API组成,也就是说不管是程序、脚本语⾔还是库⽂ 件,最终都是通过它与SQLite交互的(我们经常使⽤的ODBC/JDBC最 后也会转化为相应C API的调⽤)。
Page
19
编译器(Compiler) 编译过程从分词器(Tokenizer)和分析器(Parser)开始。它们协作处理 ⽂本形式的结构化查询(Structured Query Language, SQL)语句,分 析其语法有效性,转化为底层能更⽅便处理的层次数据结构——语法 树,然后把语法树传给代码⽣成器(code generator)进⾏处理。SQLite 分词器的代码是⼿⼯编写的,分析器代码是由SQLite定制的分析器⽣ 成器(称为Lemon)⽣成的。The Lemon parser generator is designed for high performance and takes special precautions to guard against memory leaks. ⼀旦SQL语句被分解为串值并组织到语法树中,分析 器就将该树下传给代码⽣成器进⾏处理。⽽代码⽣成器根据它⽣成⼀ 种SQLite专⽤的汇编代码,最后由虚拟机(Virtual Machine)执⾏。
Page
20
虚拟机(Virtual Machine) 架构中最核⼼的部分是虚拟机,或者叫做虚拟数据库引擎(Virtual DataBase Engine,VDBE)。它和Java虚拟机相似,解释执⾏字节代 码。VDBE的字节代码(称为虚拟机语⾔)由128个操作码(opcodes)构 成,主要是进⾏数据库操作。它的每⼀条指令或者⽤来完成特定的数 据库操作(⽐如打开⼀个表的游标、开始⼀个事务等),或者为完成这 些操作做准备。总之,所有的这些指令都是为了满⾜SQL命令的要 求。VDBE的指令集能满⾜任何复杂SQL命令的要求。所有的SQLite SQL语句——从选择和修改记录到创建表、视图和索引——都是⾸先 编译成此种虚拟机语⾔,组成⼀个独⽴程序,定义如何完成给定的命 令。例如,在SQLite的CLP中执⾏下⾯语句:
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A practical, code-first guide to SQLite that takes you from the command-line shell to the C API, covering the relational model, SQL syntax, transactions, locking, and advanced programming hooks—ideal for developers who want to embed a lightweight, zero-config database into their applications.
【Book Arc】
- **Opening (~0%–8%)**: Introduces SQLite as a unique embedded, open-source relational database with cross-platform binary compatibility and a strong reliability story (extensive regression testing). Covers installation, compiling on Windows (VC/MinGW), and the basics of the command-line shell (CLP) for creating tables, inserting data, and formatting output.
- **Early (~8%–23%)**: Moves into the relational model (tables, rows, columns) and core SQL syntax. Covers `ALTER TABLE`, the full `SELECT` statement with clauses like `WHERE`, `GROUP BY`, `HAVING`, and `ORDER BY`, plus operators like `LIKE` and `GLOB`. Introduces `INSERT` and constraints (`NOT NULL`, `CHECK`), and explains collation (BINARY, NOCASE) for text comparison.
- **Early (~23%–31%)**: Delves into SQLite's dynamic typing system—storage classes (NULL, INTEGER, REAL, TEXT, BLOB) and type affinity. Explains how values of different types are stored, compared, and sorted. Introduces transactions, deadlock scenarios, index usage rules, and database configuration via `PRAGMA` commands (e.g., `cache_size`).
- **Middle (~38%–54%)**: Transitions from SQL to the C API. Covers opening/creating databases (including in-memory databases), page size and encoding settings, prepared statements, and the `sqlite3_mprintf()` function with `%q`/`%Q` for safe SQL string handling (SQL injection defense). Explains the locking model in detail—UNLOCKED, SHARED, RESERVED, PENDING, EXCLUSIVE—and the rollback journal's role in crash recovery.
- **Late (~54%–77%)**: Focuses on the core C API in depth: the ~80 functions (only 8 essential), UTF-8/UTF-16 variants, error codes, column metadata, parameter binding, and hooks like `sqlite3_update_hook()` and the authorization callback. Covers user-defined functions, aggregates, and collations, with a note that these are connection-scoped, not stored in the database.
【Key Takeaways】
- **SQLite is the only embedded relational database designed from scratch for that purpose** (Early): Unlike Firebird or MySQL embedded variants, SQLite is fully open-source, license-free, and purpose-built for in-process use—making it a default choice for desktop, mobile, and appliance software.
- **The database file is binary-compatible across all platforms** (Early): A SQLite file created on a SPARC workstation works unchanged on Windows, Mac, or a phone, regardless of byte order or architecture. This portability is a core design guarantee, not an afterthought.
- **Dynamic typing via storage classes is the heart of SQLite's flexibility** (Early): Every value has a storage class (NULL, INTEGER, REAL, TEXT, BLOB), and columns have "affinity" that influences how values are stored. Understanding the class ordering (NULL < numbers < TEXT < BLOB) is essential for writing correct queries and avoiding surprises.
- **Transactions and locking are simple but require discipline** (Early): A transaction is an all-or-nothing boundary; concurrent connections can deadlock (e.g., one holding a reserved lock, another a shared lock). Knowing the lock states (UNLOCKED → SHARED → RESERVED → PENDING → EXCLUSIVE) helps you design conflict-free access patterns.
- **The C API is small but powerful—only 8 functions are essential** (Late): `sqlite3_open()`, `sqlite3_exec()`, `sqlite3_prepare()`, `sqlite3_step()`, `sqlite3_finalize()`, and a few others cover the full connect-query-close cycle. The remaining ~70 functions handle specific tasks like metadata, hooks, and custom functions.
- **Use `%q`/`%Q` in `sqlite3_mprintf()` to prevent SQL injection** (Middle): These format specifiers double single quotes and backslashes, making user input safe for embedding in SQL strings. This is a simple, effective defense for C applications that build queries from user input.
- **Temporary tables are a workaround for concurrency constraints** (Middle): Since temp tables live outside the database file, they don't require RESERVED locks. They let you read from a table while updating a copy, then swap—useful for complex operations that would otherwise deadlock.
- **User-defined functions, aggregates, and collations are connection-scoped** (Late): They live in your program's library, not in the database. This means they're powerful for custom logic but must be re-registered on every new connection—don't mistake them for stored procedures.
【Reading Tips】
- **Skim the opening chapters (0–8%)** if you already know SQL basics; the key value is the compatibility and reliability discussion, plus the CLP formatting commands (`.mode`, `.headers`, `.nullvalue`) which you'll use constantly.
- **Deep-read the storage class and affinity section (~23–31%)**—it's the most conceptually tricky part and explains why SQLite behaves differently from strict-typed databases. Understanding class ordering will save you from debugging weird sort or comparison results.
- **For C programmers, focus on Chapters 5–7 (~38–77%)**: the prepared statement lifecycle (`prepare` → `step` → `finalize`), error handling, and the locking model. The code examples are practical; the "empty notes" from the translator (e.g., VC6 build steps) are optional and can be skipped.
- **If you're not writing C code**, skim the API chapters and just absorb the concepts: parameter binding, hooks, and custom functions. The SQL chapters (Early) are the most universally useful.
- **Use the `EXPLAIN` command** (shown in the opening and middle sections) to see the VDBE bytecode—it's a great way to understand how SQLite executes queries and why indexes matter.
【Coverage Limits】
This guide covers the book's core content: SQL syntax, storage classes, transactions, locking, and the C API. It does not cover advanced topics like the full VDBE internals, performance tuning beyond `PRAGMA` basics, or the appendices (e.g., full C API reference), as those are not detailed in the sampled excerpts.
Passage locations
Excerpt 1
0 00 程序由17条指令组成。通过对给定的操作数完成特别的操作,这些指 令将会返回episodes表前10个记录的name字段的值。episodes表是 本书⽰例数据库的⼀部分。 兼容性 SQLite在设计时特别注意了兼容性。它可以编译运⾏在Windows、 Linux、BSD、Mac OS X及商⽤的Unix...
View in text
Excerpt 2
CT的⼦句 操作符 类型 作⽤ IN Logical In AND Logical And OR Logical Or LIKE Relational String matching GLOB Relational Filename matching LIKE操作符 ⼀个很有⽤的关系操作符是LIKE。LIKE的作...
View in text
Excerpt 3
tabases. 查看Query的执⾏ 可以⽤EXPLAIN命令查看SQLite执⾏⼀个查询的⽅法。EXPLAIN列出 ⼀个SQL命令编译后的VDBE程序。 sqlite> .m col sqlite> .h on sqlite> .w 4 15 3 3 3 10 3 sqlite> EXPLAIN SELECT...
View in text
Excerpt 4
库操作的SQLite API。第5章已经介绍了API如何⼯ 作,本章关注细节。 本章从⼏个例⼦开始,深⼊介绍C API。学完本章之后,你会看到每 个C API函数都与常⽤的数据库操作有关,包括执⾏命令、管理事 务、取记录、处理错误等等。 SQLite的版本3的API包括⼤约80个函数。只有8个函数在连接、查询 和...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay