Sqlite 简明教程
SQLite - Overview
本章帮助你理解什么是 SQLite,它与 SQL 的区别,为什么需要它,以及它如何处理应用程序数据库。
SQLite 是一个实现一个独立的、无服务器的、零配置的、事务型 SQL 数据库引擎的软件库。SQLite 是周围发展最快的数据库引擎之一,但这仅仅是流行程度的增长,与它的规模无关。SQLite 的源代码是公有域的。
What is SQLite?
SQLite 是一个实现独立的、无服务器的、零配置的、事务型 SQL 数据库引擎的进程内库。它是一个数据库,零配置,意味着和其他的数据库不同,你不需要在系统中配置它。
SQLite 引擎不是一个像其他数据库一样的独立进程,你可以根据你的需求与你的应用程序静态或动态地链接它。SQLite 直接访问它的存储文件。
Why SQLite?
-
SQLite 不要求一个单独的服务器进程或系统来操作(无服务器的)。
-
SQLite 具有零配置,这意味着不需要设置或管理。
-
一个完整的 SQLite 数据库存储在一个单一跨平台磁盘文件中。
-
SQLite 体积非常小且轻量级,完全配置后不到 400KiB,或者在省略可选功能时不到 250KiB。
-
SQLite 是独立的,这意味着没有外部依赖。
-
SQLite 事务完全符合 ACID,允许多个进程或线程安全访问。
-
SQLite 支持 SQL92 (SQL2) 标准中发现的大多数查询语言特征。
-
SQLite 是用 ANSI-C 编写的,并提供了简单易用的 API。
-
SQLite 可用于 UNIX(Linux、Mac OS-X、Android、iOS)和 Windows(Win32、WinCE、WinRT)。
SQLite A Brief History
-
2000 年 - D. Richard Hipp 设计了 SQLite,其目的是无需管理即可操作程序。
-
2000 年 - 8 月,SQLite 1.0 与 GNU 数据库管理器一起发布。
-
2011 年 - Hipp 宣布将 UNQl 接口添加到 SQLite DB 并开发 UNQLite(面向文档的数据库)。
SQLite Limitations
SQLite 中有一些不受 SQL92 支持的功能,如下表所示。
Sr.No. |
Feature & Description |
1 |
RIGHT OUTER JOIN 仅实现了左外联接。 |
2 |
FULL OUTER JOIN 仅实现了左外联接。 |
3 |
ALTER TABLE 支持 ALTER TABLE 命令的 RENAME TABLE 和 ADD COLUMN 变体。不支持 DROP COLUMN、ALTER COLUMN、ADD CONSTRAINT。 |
4 |
Trigger support 支持 FOR EACH ROW 触发器但不支持 FOR EACH STATEMENT 触发器。 |
5 |
VIEWs SQLite 中的视图是只读的。你不能对视图执行 DELETE、INSERT 或 UPDATE 语句。 |
6 |
GRANT and REVOKE 可以应用的唯一访问权限是底层操作系统的正常文件访问权限。 |
SQLite Commands
与关系数据库交互的标准 SQLite 命令类似于 SQL。它们是 CREATE、SELECT、INSERT、UPDATE、DELETE 和 DROP。可以根据操作性质将这些命令分类为不同的组 −
DDL - Data Definition Language
Sr.No. |
Command & Description |
1 |
CREATE 为数据库中的表、表视图或其他对象创建一个新表。 |
2 |
ALTER 修改现有的数据库对象(例如,表)。 |
3 |
DROP 删除表、表视图或数据库中的其他对象。 |
SQLite - Installation
SQLite 以其出色的零配置功能而闻名,这意味着不需要复杂设置或管理。本章将引导你完成在 Windows、Linux 和 Mac OS X 上设置 SQLite 的过程。
Install SQLite on Windows
-
Step 1 - 转到 SQLite download page ,并从 Windows 部分下载预编译二进制文件。
-
Step 2 - 下载 sqlite-shell-win32- .zip and sqlite-dll-win32- .zip 压缩文件。
-
Step 3 - 创建一个 C:>sqlite 文件夹,并在此文件夹中解压缩上述两个压缩文件,这会为你提供 sqlite3.def、sqlite3.dll 和 sqlite3.exe 文件。
-
Step 4 - 在 PATH 环境变量中添加 C:>sqlite,最后转到命令提示符并发出 sqlite3 命令,该命令应显示以下结果。
C:\>sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Install SQLite on Linux
如今,几乎所有版本的 Linux 操作系统都已随附 SQLite。因此,只需发出以下命令即可检查你的计算机上是否已安装 SQLite。
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
如果你看不到以上结果,则表示你的 Linux 计算机上未安装 SQLite。以下是安装 SQLite 的步骤 -
-
Step 1 - 转到 SQLite download page 并从源代码部分下载 sqlite-autoconf-*.tar.gz。
-
Step 2 − 运行以下命令 −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
上述命令将在你的 Linux 机器上完成 SQLite 的安装。你可以按照上面说明的进行验证。
Install SQLite on Mac OS X
尽管 Mac OS X 的最新版本预安装了 SQLite,但如果你没有安装,那么只需按照以下步骤操作 −
-
Step 1 − 前往 SQLite download page ,并从源代码部分下载 sqlite-autoconf-*.tar.gz。
-
Step 2 − 运行以下命令 −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
上述过程将在你的 Mac OS X 机器上完成 SQLite 的安装。你可以通过执行以下命令进行验证 −
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
最后,你将获得 SQLite 命令提示符,可以在其中为你的练习执行 SQLite 命令。
SQLite - Commands
本章将带您了解 SQLite 程序员使用的简单且有用的命令。这些命令称为 SQLite 点命令,而且这些命令的例外之处是它们不应该以分号 (;) 结束。
让我们从在命令提示符中输入一个 sqlite3 命令开始,该命令会为您提供 SQLite 命令提示符,您可以在其中发出各种 SQLite 命令。
$sqlite3
SQLite version 3.3.6
Enter ".help" for instructions
sqlite>
您可以随时输入 “.help” 来获取可用点命令的列表。例如−
sqlite>.help
上述命令将显示一个包含各种重要 SQLite 点命令的列表,这些命令列在以下表格中。
Sr.No. |
Command & Description |
1 |
.backup ?DB? FILE 将 DB(默认值为 “main”)备份至 FILE |
2 |
*.bail ON |
OFF* 在遇到错误后停止。默认值为 OFF |
3 |
.databases 列出附加数据库的名称和文件 |
4 |
.dump ?TABLE? 以 SQL 文本格式转储数据库。如果指定了表,则只转储与 TABLE 类似模式匹配的表 |
5 |
*.echo ON |
OFF*打开或关闭命令回显 |
6 |
.exit Exit SQLite prompt |
7 |
*.explain ON |
OFF*打开或关闭适合于 EXPLAIN 的输出模式。如果没有参数,它将打开 EXPLAIN |
8 |
*.header(s) ON |
OFF*打开或关闭标头的显示 |
9 |
.help Show this message |
10 |
.import FILE TABLE 从文件导入表中的数据 |
11 |
.indices ?TABLE? 显示所有索引的名称。如果指定了表,则只显示与 TABLE 类似模式匹配的表的索引 |
12 |
.load FILE ?ENTRY? 加载扩展库 |
13 |
*.log FILE |
off*打开或关闭日志记录。FILE 可以是 stderr/stdout |
14 |
.mode MODE 设置输出模式,其中模式为下列模式之一 − csv − 逗号分隔值 column − 左对齐列。 html − HTML <table> 代码 insert − TABLE 的 SQL 插入语句 line − 每行一个值 list − 值用 .separator 字符串分隔 tabs − 制表符分隔的值 tcl − TCL 列表元素 |
15 |
.nullvalue STRING 在 NULL 值位置打印字符串 |
16 |
.output FILENAME 将输出发送到文件名 |
17 |
.output stdout 将输出发送到屏幕 |
18 |
.print STRING… Print literal STRING |
19 |
.prompt MAIN CONTINUE 替换标准提示 |
20 |
.quit Exit SQLite prompt |
21 |
.read FILENAME 在 FILENAME 中执行 SQL |
22 |
.schema ?TABLE? 显示 CREATE 语句。如果指定了表,则只显示与 TABLE 类似模式匹配的表 |
23 |
.separator STRING 更改输出模式和 .import 所用的分隔符 |
24 |
.show 显示各种设置的当前值 |
25 |
*.stats ON |
OFF*打开或关闭统计 |
26 |
.tables ?PATTERN? 列出与 LIKE 模式相匹配的表名 |
27 |
.timeout MS 尝试将锁定表打开 MS 毫秒 |
28 |
.width NUM NUM 设置“列”模式的列宽 |
29 |
*.timer ON |
让我们尝试 .show 命令,以查看 SQLite 命令提示符的默认设置。
sqlite>.show
echo: off
explain: off
headers: off
mode: column
nullvalue: ""
output: stdout
separator: "|"
width:
sqlite>
确保 sqlite> 提示符和 dot 命令之间没有空格,否则将不起作用。
Formatting Output
您可以使用以下 dot 命令序列来格式化输出。
sqlite>.header on
sqlite>.mode column
sqlite>.timer on
sqlite>
以上设置将按以下格式生成输出。
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
CPU Time: user 0.000000 sys 0.000000
SQLite - Syntax
SQLite 是遵循称为语法的一组独特规则和指南的。本章列出了所有基本的 SQLite 语法。
Case Sensitivity
需要注意的重要一点是,SQLite 是 case insensitive ,但有些命令是区分大小写的,例如 GLOB 和 glob 在 SQLite 语句中具有不同的含义。
Comments
SQLite 注释是额外的注释,可以将其添加到 SQLite 代码中以提高其可读性,它们可以出现在任何地方;空格可能会出现,包括在表达式内部和其它 SQL 语句的中部,但不能嵌套。
SQL 注释以两个连续的 "-" 字符(ASCII 0x2d)开头,并扩展到下一个换行符(ASCII 0x0a)或输入结束,以先到者为准。
你还可以使用 C 风格注释,它以字符对 "/ " and extend up to and including the next " /" 开头,或以输入结束,以先到者为准。C 风格注释可以跨越多行。
sqlite> .help -- This is a single line comment
SQLite Statements
所有 SQLite 语句都以任意关键字开头,如 SELECT、INSERT、UPDATE、DELETE、ALTER、DROP 等,所有语句都以分号 (;) 结尾。
SQLite AND/OR Clause
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
SQLite BETWEEN Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SQLite CREATE UNIQUE INDEX Statement
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
SQLite CREATE TABLE Statement
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
SQLite CREATE TRIGGER Statement
CREATE TRIGGER database_name.trigger_name
BEFORE INSERT ON table_name FOR EACH ROW
BEGIN
stmt1;
stmt2;
....
END;
SQLite CREATE VIRTUAL TABLE Statement
CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log );
or
CREATE VIRTUAL TABLE database_name.table_name USING fts3( );
SQLite EXISTS Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name EXISTS (SELECT * FROM table_name );
SQLite GLOB Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name GLOB { PATTERN };
SQLite GROUP BY Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQLite HAVING Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
SQLite INSERT INTO Statement
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
SQLite IN Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SQLite Like Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SQLite NOT IN Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name NOT IN (val-1, val-2,...val-N);
SQLite ORDER BY Clause
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SQLite PRAGMA Statement
PRAGMA pragma_name;
For example:
PRAGMA page_size;
PRAGMA cache_size = 1024;
PRAGMA table_info(table_name);
SQLite REINDEX Statement
REINDEX collation_name;
REINDEX database_name.index_name;
REINDEX database_name.table_name;
SQLite - Data Type
SQLite 数据类型是一种属性,用于指定任何对象的类型。SQLite 中的每一列、变量和表达式都具有相关的数据类型。
在创建表时会使用这些数据类型。SQLite 使用一个更通用的动态类型系统。在 SQLite 中,一个值的数据类型与其自身关联,而不仅仅与其容器相关联。
SQLite Storage Classes
存储在 SQLite 数据库中的每个值都具有以下存储类之一 −
Sr.No. |
Storage Class & Description |
1 |
NULL 值为 NULL 值。 |
2 |
INTEGER 值为有符号整数,以 1、2、3、4、6 或 8 个字节存储,具体取决于值的大小。 |
3 |
REAL 值为浮点值,以 8 字节 IEEE 浮点数字存储。 |
4 |
TEXT 值为文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储 |
5 |
BLOB 这个值是数据块,存储的时候就是输入的样子。 |
SQLite 存储类比数据类型要略为更通用。例如,INTEGER 存储类包括6种不同长度的不同整数数据类型。
SQLite Affinity Type
SQLite 支持{@s1}在列上的概念。任何列仍然可以存储任何类型的数据,但是列的首选存储类被称作其{@s2}。SQLite3 数据库中的每一张表都被分配以下类型关联中的一个 −
Sr.No. |
Affinity & Description |
1 |
TEXT 此列使用存储类 NULL、TEXT 或 BLOB 存储所有数据。 |
2 |
NUMERIC 此列可以使用所有五个存储类来包含值。 |
3 |
INTEGER 与 NUMERIC 关联的列的行为类似,在 CAST 表达式中除外。 |
4 |
REAL 与 NUMERIC 关联的列的行为类似,但它会强行将整数的值转换为浮点数表示。 |
5 |
NONE 关联为 NONE 的列不会优先考虑某种存储类,也不会尝试将数据从一种存储类强制转换为另一种存储类。 |
SQLite Affinity and Type Names
下表列出了在使用相应的应用关联创建 SQLite3 时可用于创建 SQLite3 数据库的各种数据类型名称。
Data Type |
Affinity |
INTINTEGERTINYINTSMALLINTMEDIUMINTBIGINTUNSIGNED BIG INTINT2INT8 |
INTEGER |
CHARACTER(20)VARCHAR(255)VARYING CHARACTER(255)NCHAR(55)NATIVE CHARACTER(70)NVARCHAR(100)TEXTCLOB |
TEXT |
BLOBno datatype specified |
NONE |
REALDOUBLEDOUBLE PRECISIONFLOAT |
REAL |
NUMERICDECIMAL(10,5)BOOLEANDATEDATETIME |
NUMERIC |
SQLite - CREATE Database
在 SQLite 中, sqlite3 命令用于创建一个新的 SQLite 数据库。你不必有任何特殊权限来创建数据库。
Example
如果你想创建一个新数据库 <testDB.db>,则 SQLITE3 语句如下所示−
$sqlite3 testDB.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
上述命令将在当前目录中创建一个文件 testDB.db 。此文件将被 SQLite 引擎用作数据库。如果你在创建数据库时注意到,在成功创建数据库文件后,sqlite3 命令将提供一个 sqlite> 提示。
创建数据库后,你可以使用以下 SQLite *.databases * 命令在数据库列表中进行验证。
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
你将使用 SQLite .quit 命令按照以下方式退出 sqlite 提示−
sqlite>.quit
$
The .dump Command
你可以使用 .dump 句点命令使用以下 SQLite 命令在命令提示符下将完整数据库导出到文本文件中。
$sqlite3 testDB.db .dump > testDB.sql
上述命令会将 testDB.db 数据库的整个内容转换为 SQLite 语句,并将其转储到 ASCII 文本文件 testDB.sql 中。你可以按如下所示的方式从生成的 testDB.sql 中以简单的方式执行还原−
$sqlite3 testDB.db < testDB.sql
此刻你的数据库是空的,所以一旦你的数据库中有一些表和数据,你可以尝试以上两个过程。现在,让我们继续下一章。
SQLite - ATTACH Database
考虑一个案例:您有多个可用的数据库,您只想每次使用其中一个。SQLite ATTACH DATABASE 语句用于选择特定数据库,此命令之后,所有的 SQLite 语句都将在所附加的数据库中执行。
Syntax
以下是 SQLite ATTACH DATABASE 语句的基本语法。
ATTACH DATABASE 'DatabaseName' As 'Alias-Name';
如果数据库尚未创建,以上命令还会创建一个数据库,否则只将数据库文件名附加到逻辑数据库“别名”。
Example
如果您希望附加一个现有数据库 testDB.db ,则 ATTACH DATABASE 语句如下 −
sqlite> ATTACH DATABASE 'testDB.db' as 'TEST';
使用 SQLite .database 命令显示附加的数据库。
sqlite> .database
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
数据库名 main 和 temp 分别为主要数据库和保存临时表和其他临时数据对象的数据库保留。这两个数据库名每个数据库连接都存在,不应用于附加,否则您将收到以下警告信息。
sqlite> ATTACH DATABASE 'testDB.db' as 'TEMP';
Error: database TEMP is already in use
sqlite> ATTACH DATABASE 'testDB.db' as 'main';
Error: database TEMP is already in use
SQLite - DETACH Database
SQLite DETACH DATABASE 语句用于分离和解除与先前使用 ATTACH 语句附加的数据库连接的已命名数据库。如果已使用多个别名附加了相同的数据库文件,DETACH 命令将仅断开提供的名称,其余附加仍然将继续。无法分离 main 或 temp 数据库。
如果数据库是内存中或临时数据库,数据库将被销毁,并且内容将丢失。
Syntax
以下是 SQLite DETACH DATABASE 'Alias-Name' 语句的基本语法。
DETACH DATABASE 'Alias-Name';
此处,“别名名称”是使用 ATTACH 语句附加数据库时使用的相同别名。
Example
考虑你有在上一章中创建的数据库,并使用“测试”和“currentDB”附加它,如我们使用 .database 命令所见。
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
3 currentDB /home/sqlite/testDB.db
让我们尝试使用以下命令从 testDB.db 中分离 “currentDB”。
sqlite> DETACH DATABASE 'currentDB';
现在,如果你检查当前附件,你会发现 testDB.db 仍然与 “test” 和 “main” 相连。
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
SQLite - CREATE Table
SQLite CREATE TABLE 语句用于在给定的任何数据库中创建新表。创建基本表包括对表命名以及为其列和每个列的数据类型定义。
Syntax
以下是 CREATE TABLE 语句的基本语法。
CREATE TABLE database_name.table_name(
column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
.....
columnN datatype
);
CREATE TABLE 是一个关键字,用于指示数据库系统创建新表。CREATE TABLE 语句后面跟表唯一的名称或标识符。可以选择指定 database_name 和 table_name。
Example
以下是一个示例,它使用 ID 创建一个 COMPANY 表,其中 ID 为主键,并且 NOT NULL 是约束,它表明在表中创建记录时这些字段不能为 NULL。
sqlite> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
让我们在后续章节中创建另一个表,我们将在我们的练习中使用该表。
sqlite> CREATE TABLE DEPARTMENT(
ID INT PRIMARY KEY NOT NULL,
DEPT CHAR(50) NOT NULL,
EMP_ID INT NOT NULL
);
您可以使用 SQLite 命令 .tables 来验证是否成功创建了该表,该命令将用于列出附加数据库中的所有表。
sqlite>.tables
COMPANY DEPARTMENT
在这里,您可以看到 COMPANY 表两次,因为它显示了 main 数据库的 COMPANY 表以及为 testDB.db 创建的“test”别名的 test.COMPANY 表。您可以使用以下 SQLite .schema 命令获取有关表的完整信息。
sqlite>.schema COMPANY
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
SQLite - DROP Table
SQLite DROP TABLE 语句用于删除表定义及其相关的所有数据、索引、触发器、约束和权限规范。
使用此命令时必须小心,因为一旦表被删除,表中所有可用的信息也将永远丢失。
SQLite - INSERT Query
SQLite INSERT INTO 语句用于将新数据行添加到数据库中的表中。
Syntax
以下是 INSERT INTO 语句的两个基本语法:
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
这里,column1、column2、…columnN 是想要在其中插入数据表的列的名称。
如果要为表的全部列添加值,则可能不需要在 SQLite 查询中指定列的名称。但是,确保值的顺序与表中的列顺序相同。SQLite INSERT INTO 语法如下所示:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example
假设你已经按照以下方式在 testDB.db 中创建了 COMPANY 表:
sqlite> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
现在,以下语句将在 COMPANY 表中创建六条记录。
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'David', 27, 'Texas', 85000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 );
可以使用第二个语法在 COMPANY 表中创建记录,如下所示:
INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 );
以上所有语句将在 COMPANY 表中创建以下记录。在下一章中,你将学习如何从表中显示所有这些记录。
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
SQLite - SELECT Query
SQLite SELECT 语句用于从 SQLite 数据库表中获取数据,它以结果表的形式返回数据。这些结果表也称为 result sets 。
Syntax
以下是 SQLite SELECT 语句的基本语法。
SELECT column1, column2, columnN FROM table_name;
此处,column1、column2 … 是要获取其值的一个表的字段。如果您想要获取字段中可用的所有字段,则可以使用以下语法 −
SELECT * FROM table_name;
Example
考虑具有以下记录的 COMPANY 表 -
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
以下是使用 SELECT 语句获取并显示所有这些记录的示例。此处,前三条命令被用来设置适当格式的输出。
sqlite>.header on
sqlite>.mode column
sqlite> SELECT * FROM COMPANY;
最后,您将获得以下结果。
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
如果您只想要获取 COMPANY 表的某些选定字段,则使用以下查询 −
sqlite> SELECT ID, NAME, SALARY FROM COMPANY;
上述查询将产生以下结果。
ID NAME SALARY
---------- ---------- ----------
1 Paul 20000.0
2 Allen 15000.0
3 Teddy 20000.0
4 Mark 65000.0
5 David 85000.0
6 Kim 45000.0
7 James 10000.0
Setting Output Column Width
有时候,您会遇到 .mode column 中关于截断输出的问题,这是因为要显示的列的默认宽度导致的。您可以做的就是使用 .width num, num…. 命令设置列显示列宽,如下所示 −
sqlite>.width 10, 20, 10
sqlite>SELECT * FROM COMPANY;
上述 .width 命令将第一列宽设置为 10,第二列宽设置为 20,第三列宽设置为 10。最后,上述 SELECT 语句将给出以下结果。
ID NAME AGE ADDRESS SALARY
---------- -------------------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Schema Information
既然所有 dot commands 都在 SQLite 提示中可用,因此在用 SQLite 编程时,将使用与 sqlite_master 表关联的以下 SELECT 语句,列出在数据库中创建的所有表。
sqlite> SELECT tbl_name FROM sqlite_master WHERE type = 'table';
假设你的 testDB.db 中只有 COMPANY 表,就会生成以下结果。
tbl_name
----------
COMPANY
你可以按如下方式列出 COMPANY 表的完整信息:
sqlite> SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = 'COMPANY';
假设你的 testDB.db 中只有 COMPANY 表,就会生成以下结果。
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
)
SQLite - Operators
What is an Operator in SQLite?
运算符是保留字或字符,主要用于 SQLite 语句的 WHERE 子句中,用于执行操作(例如比较和算术运算)。
运算符用于指定 SQLite 语句中的条件,并作为语句中多个条件的连接词。
-
Arithmetic operators
-
Comparison operators
-
Logical operators
-
Bitwise operators
SQLite Arithmetic Operators
假设变量 a 保存 10 而变量 b 保存 20,那么 SQLite 算术运算符将按如下方式使用 −
Operator |
Description |
Example |
+ (Addition) |
添加运算符两侧的值 |
a + b 将得到 30 |
- (Subtraction) |
从左操作数减去右操作数 |
a - b 将得到 -10 |
* (Multiplication) |
乘以运算符两侧的值 |
a * b 将得到 200 |
/ (Division) |
将左操作数除以右操作数 |
b / a 将得到 2 |
% (Modulus) |
将左操作数除以右操作数并返回余数 |
b % a 将得到 0 |
SQLite Comparison Operators
假设变量 a 保存 10 而变量 b 保存 20,那么 SQLite 比较运算符将按如下方式使用
Operator |
Description |
Example |
== |
检查两个操作数的值是否相等,如果相等则条件为真。 |
(a == b)为 false。 |
= |
检查两个操作数的值是否相等,如果相等则条件为真。 |
(a = b) 不为真。 |
!= |
检查两个操作数的值是否相等,如果不相等,则条件为真。 |
(a != b) 为 true。 |
<> |
检查两个操作数的值是否相等,如果不相等,则条件为真。 |
(a <> b) 为真。 |
> |
检查左操作数的值是否大于右操作数的值,如果大于,则条件为真。 |
(a > b) 为 false。 |
< |
检查左操作数的值是否小于右操作数的值,如果小于,则条件为真。 |
(a < b) 为 true。 |
>= |
检查左操作数的值是否大于或等于右操作数的值,如果大于或等于,则条件为真。 |
(a >= b) 为 false。 |
⇐ |
检查左操作数的值是否小于或等于右操作数的值,如果小于或等于,则条件为真。 |
(a ⇐ b) 为 true。 |
!< |
检查左操作数的值是否不小于右操作数的值,如果不小于,则条件为真。 |
(a !< b) 为假。 |
!> |
检查左操作数的值是否不大于右操作数的值,如果不大于,则条件为真。 |
(a !> b) 为真。 |
SQLite Logical Operators
下面是 SQLite 中提供的所有逻辑运算符的列表。
Sr.No. |
Operator & Description |
1 |
AND AND 运算符允许在 SQL 语句的 WHERE 子句中存在多个条件。 |
2 |
BETWEEN BETWEEN 运算符用于搜索给定最小值和最大值的集合值。 |
3 |
EXISTS EXISTS 运算符可用于在符合特定条件的指定表中搜索某行的存在。 |
4 |
IN IN 运算符用于将一个值与已指定的一系列文本值进行比较。 |
5 |
NOT IN IN 运算符的否定,可用于将值与已指定的文本值列表比较。 |
6 |
LIKE LIKE 运算符用于在使用通配符运算符时将一个值与类似的值进行比较。 |
7 |
GLOB GLOB 运算符可用于使用通配符运算符将值与相似值比较。此外,与 LIKE 不同的是,GLOB 区分大小写。 |
8 |
NOT NOT 运算符反转其所用逻辑运算符的含义。例如,NOT EXISTS、NOT BETWEEN、NOT IN 等。 This is negate operator. |
9 |
OR OR 运算符用于组合 SQL 语句 WHERE 子句中的多个条件。 |
10 |
IS NULL NULL 运算符用于将一个值与 NULL 值进行比较。 |
11 |
IS IS 运算符的工作方式类似于 = |
12 |
IS NOT IS 运算符的工作方式类似于 != |
13 |
* |
* 将两个不同的字符串相加并生成一个新字符串。 |
|
14 |
UNIQUE UNIQUE 操作符搜索指定表的每行以查找唯一性(没有重复项)。 |
SQLite Bitwise Operators
按位运算符对位进行操作,并执行按位运算。以下是 & 和 | 的真值表。
p |
q |
p & |
p |
q |
0 |
0 |
0 |
0 |
0 |
1 |
0 |
1 |
1 |
1 |
1 |
1 |
1 |
0 |
0 |
假设如果 A = 60;且 B = 13,那么在二进制格式中,它们如下所示 −
A = 0011 1100
B = 0000 1101
A&B = 0000 1100 A|B = 0011 1101 ~A = 1100 0011 The Bitwise operators supported by SQLite language are listed in the following table. Assume variable *A* holds 60 and variable *B* holds 13, then − link:../sqlite/sqlite_bitwise_operators.html[Show Examples] [%autowidth] |=== |Operator|Description|Example |&|Binary AND Operator copies a bit to the result, if it exists in both operands.|(A & B) will give 12 which is 0000 1100 |||Binary OR Operator copies a bit, if it exists in either operand.|(A | B) will give 61 which is 0011 1101 |~|Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.|(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number |<<|Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.|A << 2 will give 240 which is 1111 0000 |>>|Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.|A >> 2 will give 15 which is 0000 1111 |=== == SQLite - Expressions An expression is a combination of one or more values, operators, and SQL functions that evaluate to a value. SQL expressions are like formulas and they are written in query language. You can also use to query the database for a specific set of data. ==== Syntax Consider the basic syntax of the SELECT statement as follows − [source]
SELECT column1, column2, columnN FROM table_name WHERE [CONDITION | EXPRESSION];
Following are the different types of SQLite expressions. === SQLite - Boolean Expressions SQLite Boolean Expressions fetch the data on the basis of matching single value. Following is the syntax − [source]
SELECT column1, column2, columnN FROM table_name WHERE SINGLE VALUE MATCHTING EXPRESSION;
Consider COMPANY table with the following records − [source]
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
Following is a simple examples showing the usage of SQLite Boolean Expressions − [source]
sqlite> SELECT * FROM COMPANY WHERE SALARY = 10000;
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 James 24 Houston 10000.0
=== SQLite - Numeric Expression These expressions are used to perform any mathematical operation in any query. Following is the syntax − [source]
SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE CONDITION] ;
Here, numerical_expression is used for mathematical expression or any formula. Following is a simple example showing the usage of SQLite Numeric Expressions. [source]
sqlite> SELECT (15 + 6) AS ADDITION ADDITION = 21
There are several built-in functions such as *avg(), sum(), count(),* etc., to perform what is known as *aggregate data calculations* against a table or a specific table column. [source]
sqlite> SELECT COUNT(*) AS "RECORDS" FROM COMPANY; RECORDS = 7
=== SQLite - Date Expressions Date Expressions returns the current system date and time values. These expressions are used in various data manipulations. [source]
sqlite> SELECT CURRENT_TIMESTAMP; CURRENT_TIMESTAMP = 2013-03-17 10:43:35
== SQLite - WHERE Clause SQLite *WHERE* clause is used to specify a condition while fetching the data from one table or multiple tables. If the given condition is satisfied, means true, then it returns the specific value from the table. You will have to use WHERE clause to filter the records and fetching only necessary records. The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which will be covered in subsequent chapters. === Syntax Following is the basic syntax of SQLite SELECT statement with WHERE clause. [source]
SELECT column1, column2, columnN FROM table_name WHERE [condition]
=== Example You can specify a condition using link:../sqlite/sqlite_operators.html[Comparision or Logical Operators] such as >, <, =, LIKE, NOT, etc. Consider COMPANY table with the following records − [source]
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
Following is a simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 *AND* salary is greater than or equal to 65000.00. [source]
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25 *OR* salary is greater than or equal to 65000.00. [source]
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record has AGE equal to NULL. [source]
sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'. [source]
sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'. [source]
sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where AGE value is either 25 or 27. [source]
sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE value is neither 25 nor 27. [source]
sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27. [source]
sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0
Following SELECT statement makes use of SQL sub-query, where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query − [source]
sqlite> SELECT AGE FROM COMPANY WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
AGE
32 25 23 25 27 22 24 ---- Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query. [source] ---- sqlite> SELECT * FROM COMPANY WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000); ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 ---- == SQLite - AND & OR Operators SQLite *AND* & *OR* operators are used to compile multiple conditions to narrow down the selected data in an SQLite statement. These two operators are called *conjunctive operators*. These operators provide a means to make multiple comparisons with different operators in the same SQLite statement. === The AND Operator The *AND* operator allows the existence of multiple conditions in a SQLite statement's WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true. ==== Syntax Following is the basic syntax of AND operator with WHERE clause. [source] ---- SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]...AND [conditionN]; ---- You can combine *N* number of conditions using AND operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE. ==== Example Consider COMPANY table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following SELECT statement lists down all the records where AGE is greater than or equal to 25 *AND* salary is greater than or equal to 65000.00. [source] ---- sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- === The OR Operator The OR operator is also used to combine multiple conditions in a SQLite statement's WHERE clause. While using OR operator, complete condition will be assumed true when at least any of the conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or condition2 is true. ==== Syntax Following is the basic syntax of OR operator with WHERE clause. [source] ---- SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...OR [conditionN] ---- You can combine *N* number of conditions using OR operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE. ==== Example Consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following SELECT statement lists down all the records where AGE is greater than or equal to 25 *OR* salary is greater than or equal to 65000.00. [source] ---- sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- == SQLite - UPDATE Query SQLite *UPDATE* Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be updated. === Syntax Following is the basic syntax of UPDATE query with WHERE clause. [source] ---- UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; ---- You can combine *N* number of conditions using AND or OR operators. === Example Consider COMPANY table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will update ADDRESS for a customer whose ID is 6. [source] ---- sqlite> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6; ---- Now, COMPANY table will have the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 Texas 45000.0 7 James 24 Houston 10000.0 ---- If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not need to use WHERE clause and UPDATE query will be as follows − [source] ---- sqlite> UPDATE COMPANY SET ADDRESS = 'Texas', SALARY = 20000.00; ---- Now, COMPANY table will have the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 Texas 20000.0 2 Allen 25 Texas 20000.0 3 Teddy 23 Texas 20000.0 4 Mark 25 Texas 20000.0 5 David 27 Texas 20000.0 6 Kim 22 Texas 20000.0 7 James 24 Texas 20000.0 ---- == SQLite - DELETE Query SQLite *DELETE* Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows, otherwise all the records would be deleted. === Syntax Following is the basic syntax of DELETE query with WHERE clause. [source] ---- DELETE FROM table_name WHERE [condition]; ---- You can combine *N* number of conditions using AND or OR operators. === Example Consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will DELETE a customer whose ID is 7. [source] ---- sqlite> DELETE FROM COMPANY WHERE ID = 7; ---- Now COMPANY table will have the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 ---- If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE query, which will be as follows − [source] ---- sqlite> DELETE FROM COMPANY; ---- Now, COMPANY table does not have any record as all the records have been deleted by DELETE statement. == SQLite - LIKE Clause SQLite *LIKE* operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator − . The percent sign (%) . The underscore (_) The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations. === Syntax Following is the basic syntax of % and _. [source] ---- SELECT FROM table_name WHERE column LIKE 'XXXX%' or SELECT FROM table_name WHERE column LIKE '%XXXX%' or SELECT FROM table_name WHERE column LIKE 'XXXX_' or SELECT FROM table_name WHERE column LIKE '_XXXX' or SELECT FROM table_name WHERE column LIKE '_XXXX_' ---- You can combine *N* number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value. === Example Following table lists a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators. [%autowidth] |=== |Sr.No.|Statement & Description |1|*WHERE SALARY LIKE '200%'* Finds any values that start with 200 |2|*WHERE SALARY LIKE '%200%'* Finds any values that have 200 in any position |3|*WHERE SALARY LIKE '_00%'* Finds any values that have 00 in the second and third positions |4|*WHERE SALARY LIKE '2_%_%'* Finds any values that start with 2 and are at least 3 characters in length |5|*WHERE SALARY LIKE '%2'* Finds any values that end with 2 |6|*WHERE SALARY LIKE '_2%3'* Finds any values that has a 2 in the second position and ends with a 3 |7|*WHERE SALARY LIKE '2___3'* Finds any values in a five-digit number that starts with 2 and ends with 3 |=== Let us take a real example, consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will display all the records from COMPANY table where AGE starts with 2. [source] ---- sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%'; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text. [source] ---- sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%'; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0 ---- == SQLite - GLOB Clause SQLite *GLOB* operator is used to match only text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of UNIX for specifying THE following wildcards. . The asterisk sign (*) . The question mark (?) The asterisk sign (*) represents zero or multiple numbers or characters. The question mark (?) represents a single number or character. === Syntax Following is the basic syntax of *** and *?*. [source] ---- SELECT FROM table_name WHERE column GLOB 'XXXX*' or SELECT FROM table_name WHERE column GLOB '*XXXX*' or SELECT FROM table_name WHERE column GLOB 'XXXX?' or SELECT FROM table_name WHERE column GLOB '?XXXX' or SELECT FROM table_name WHERE column GLOB '?XXXX?' or SELECT FROM table_name WHERE column GLOB '????' ---- You can combine *N* number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value. === Example Following table lists a number of examples showing WHERE part having different LIKE clause with '*' and '?' operators. [%autowidth] |=== |Sr.No.|Statement & Description |1|*WHERE SALARY GLOB '200*'* Finds any values that start with 200 |2|*WHERE SALARY GLOB '*200*'* Finds any values that have 200 in any position |3|*WHERE SALARY GLOB '?00*'* Finds any values that have 00 in the second and third positions |4|*WHERE SALARY GLOB '2??'* Finds any values that start with 2 and are at least 3 characters in length |5|*WHERE SALARY GLOB '*2'* Finds any values that end with 2 |6|*WHERE SALARY GLOB '?2*3'* Finds any values that have a 2 in the second position and end with a 3 |7|*WHERE SALARY GLOB '2???3'* Finds any values in a five-digit number that start with 2 and end with 3 |=== Let us take a real example, consider COMPANY table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will display all the records from COMPANY table, where AGE starts with 2. [source] ---- sqlite> SELECT * FROM COMPANY WHERE AGE GLOB '2*'; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text − [source] ---- sqlite> SELECT * FROM COMPANY WHERE ADDRESS GLOB '*-*'; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0 ---- == SQLite - LIMIT Clause SQLite *LIMIT* clause is used to limit the data amount returned by the SELECT statement. === Syntax Following is the basic syntax of SELECT statement with LIMIT clause. [source] ---- SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] ---- Following is the syntax of LIMIT clause when it is used along with OFFSET clause. [source] ---- SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] OFFSET [row num] ---- SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example. === Example Consider COMPANY table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which limits the row in the table according to the number of rows you want to fetch from table. [source] ---- sqlite> SELECT * FROM COMPANY LIMIT 6; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 ---- However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position. [source] ---- sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- == SQLite - ORDER BY Clause SQLite *ORDER BY* clause is used to sort the data in an ascending or descending order, based on one or more columns. === Syntax Following is the basic syntax of ORDER BY clause. [source] ---- SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; ---- You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in the column-list. === Example Consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example, which will sort the result in descending order by SALARY. [source] ---- sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 7 James 24 Houston 10000.0 2 Allen 25 Texas 15000.0 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- Following is an example, which will sort the result in descending order by NAME and SALARY. [source] ---- sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 5 David 27 Texas 85000.0 7 James 24 Houston 10000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 ---- Following is an example, which will sort the result in descending order by NAME. [source] ---- sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 3 Teddy 23 Norway 20000.0 1 Paul 32 California 20000.0 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 5 David 27 Texas 85000.0 2 Allen 25 Texas 15000.0 ---- == SQLite - GROUP BY Clause SQLite *GROUP BY * clause is used in collaboration with the SELECT statement to arrange identical data into groups. GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause. === Syntax Following is the basic syntax of GROUP BY clause. GROUP BY clause must follow the conditions in the WHERE clause and must precede ORDER BY clause if one is used. [source] ---- SELECT column-list FROM table_name WHERE [ conditions ] GROUP BY column1, column2....columnN ORDER BY column1, column2....columnN ---- You can use more than one column in the GROUP BY clause. Make sure whatever column you are using to group, that column should be available in the column-list. === Example Consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- If you want to know the total amount of salary on each customer, then GROUP BY query will be as follows − [source] ---- sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME; ---- This will produce the following result − [source] ---- NAME SUM(SALARY) ---------- ----------- Allen 15000.0 David 85000.0 James 10000.0 Kim 45000.0 Mark 65000.0 Paul 20000.0 Teddy 20000.0 ---- Now, let us create three more records in COMPANY table using the following INSERT statements. [source] ---- INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00 ); INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00 ); INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00 ); ---- Now, our table has the following records with duplicate names. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 8 Paul 24 Houston 20000.0 9 James 44 Norway 5000.0 10 James 45 Texas 5000.0 ---- Again, let us use the same statement to group-by all the records using NAME column as follows − [source] ---- sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME; ---- This will produce the following result. [source] ---- NAME SUM(SALARY) ---------- ----------- Allen 15000 David 85000 James 20000 Kim 45000 Mark 65000 Paul 40000 Teddy 20000 ---- Let us use ORDER BY clause along with GROUP BY clause as follows − [source] ---- sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME DESC; ---- This will produce the following result. [source] ---- NAME SUM(SALARY) ---------- ----------- Teddy 20000 Paul 40000 Mark 65000 Kim 45000 James 20000 David 85000 Allen 15000 ---- == SQLite - HAVING Clause HAVING clause enables you to specify conditions that filter which group results appear in the final results. The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by GROUP BY clause. === Syntax Following is the position of HAVING clause in a SELECT query. [source] ---- SELECT FROM WHERE GROUP BY HAVING ORDER BY ---- HAVING clause must follow GROUP BY clause in a query and must also precede ORDER BY clause if used. Following is the syntax of the SELECT statement, including HAVING clause. [source] ---- SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2 ---- === Example Consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 8 Paul 24 Houston 20000.0 9 James 44 Norway 5000.0 10 James 45 Texas 5000.0 ---- Following is the example, which will display the record for which the name count is less than 2. [source] ---- sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000 5 David 27 Texas 85000 6 Kim 22 South-Hall 45000 4 Mark 25 Rich-Mond 65000 3 Teddy 23 Norway 20000 ---- Following is the example, which will display the record for which the name count is greater than 2. [source] ---- sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 10 James 45 Texas 5000 ---- == SQLite - DISTINCT Keyword SQLite *DISTINCT* keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only the unique records. There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records. === Syntax Following is the basic syntax of DISTINCT keyword to eliminate duplicate records. [source] ---- SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition] ---- === Example Consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 8 Paul 24 Houston 20000.0 9 James 44 Norway 5000.0 10 James 45 Texas 5000.0 ---- First, let us see how the following SELECT query returns duplicate salary records. [source] ---- sqlite> SELECT name FROM COMPANY; ---- This will produce the following result. [source] ---- NAME
Paul Allen Teddy Mark David Kim James Paul James James
Now, let us use *DISTINCT* keyword with the above SELECT query and see the result. [source]
sqlite> SELECT DISTINCT name FROM COMPANY;
This will produce the following result, where there is no duplicate entry. [source]
NAME
Paul Allen Teddy Mark David Kim James ---- == SQLite - PRAGMA SQLite *PRAGMA* command is a special command to be used to control various environmental variables and state flags within the SQLite environment. A PRAGMA value can be read and it can also be set based on the requirements. ==== Syntax To query the current PRAGMA value, just provide the name of the pragma. [source] ---- PRAGMA pragma_name; ---- To set a new value for PRAGMA, use the following syntax. [source] ---- PRAGMA pragma_name = value; ---- The set mode can be either the name or the integer equivalent but the returned value will always be an integer. === auto_vacuum Pragma The *auto_vacuum* pragma gets or sets the auto-vacuum mode. Following is the simple syntax. [source] ---- PRAGMA [database.]auto_vacuum; PRAGMA [database.]auto_vacuum = mode; ---- Where *mode* can be any of the following − [%autowidth] |=== |Sr.No.|Pragma Value & Description |1|*0 or NONE* Auto-vacuum is disabled. This is the default mode which means that a database file will never shrink in size unless it is manually vacuumed using the VACUUM command. |2|*1 or FULL* Auto-vacuum is enabled and fully automatic which allows a database file to shrink as data is removed from the database. |3|*2 or INCREMENTAL* Auto-vacuum is enabled but must be manually activated. In this mode the reference data is maintained, but free pages are simply put on the free list. These pages can be recovered using the *incremental_vacuum pragma* any time. |=== === cache_size Pragma The *cache_size* pragma can get or temporarily set the maximum size of the in-memory page cache. Following is the simple syntax. [source] ---- PRAGMA [database.]cache_size; PRAGMA [database.]cache_size = pages; ---- The *pages* value represents the number of pages in the cache. The built-in page cache has a default size of 2,000 pages and a minimum size of 10 pages. === case_sensitive_like Pragma The *case_sensitive_like* pragma controls the case-sensitivity of the built-in LIKE expression. By default, this pragma is false which means that the built-in LIKE operator ignores the letter case. Following is the simple syntax. [source] ---- PRAGMA case_sensitive_like = [true|false]; ---- There is no way to query for the current state of this pragma. === count_changes Pragma *count_changes* pragma gets or sets the return value of data manipulation statements such as INSERT, UPDATE and DELETE. Following is the simple syntax. [source] ---- PRAGMA count_changes; PRAGMA count_changes = [true|false]; ---- By default, this pragma is false and these statements do not return anything. If set to true, each of the mentioned statement will return a one-column, one-row table consisting of a single integer value indicating impacted rows by the operation. === database_list Pragma The *database_list* pragma will be used to list down all the databases attached. Following is the simple syntax. [source] ---- PRAGMA database_list; ---- This pragma will return a three-column table with one row per open or attached database giving database sequence number, its name and the file associated. === encoding Pragma The *encoding* pragma controls how strings are encoded and stored in a database file. Following is the simple syntax. [source] ---- PRAGMA encoding; PRAGMA encoding = format; ---- The format value can be one of *UTF-8, UTF-16le*, or *UTF-16be*. === freelist_count Pragma The *freelist_count* pragma returns a single integer indicating how many database pages are currently marked as free and available. Following is the simple syntax. [source] ---- PRAGMA [database.]freelist_count; ---- The format value can be one of *UTF-8, UTF-16le*, or *UTF-16be*. === index_info Pragma The *index_info* pragma returns information about a database index. Following is the simple syntax. [source] ---- PRAGMA [database.]index_info( index_name ); ---- The result set will contain one row for each column contained in the index giving column sequence, column index with-in table and column name. === index_list Pragma *index_list* pragma lists all of the indexes associated with a table. Following is the simple syntax. [source] ---- PRAGMA [database.]index_list( table_name ); ---- The result set will contain one row for each index giving index sequence, index name and flag indicating whether the index is unique or not. === journal_mode Pragma The *journal_mode* pragma gets or sets the journal mode which controls how the journal file is stored and processed. Following is the simple syntax. [source] ---- PRAGMA journal_mode; PRAGMA journal_mode = mode; PRAGMA database.journal_mode; PRAGMA database.journal_mode = mode; ---- There are five supported journal modes as listed in the following table. [%autowidth] |=== |Sr.No.|Pragma Value & Description |1|*DELETE* This is the default mode. Here at the conclusion of a transaction, the journal file is deleted. |2|*TRUNCATE* The journal file is truncated to a length of zero bytes. |3|*PERSIST* The journal file is left in place, but the header is overwritten to indicate the journal is no longer valid. |4|*MEMORY* The journal record is held in memory, rather than on disk. |5|*OFF* No journal record is kept. |=== === max_page_count Pragma The *max_page_count* pragma gets or sets the maximum allowed page count for a database. Following is the simple syntax. [source] ---- PRAGMA [database.]max_page_count; PRAGMA [database.]max_page_count = max_page; ---- The default value is 1,073,741,823 which is one giga-page, which means if the default 1 KB page size, this allows databases to grow up to one terabyte. === page_count Pragma The *page_count* pragma returns in the current number of pages in the database. Following is the simple syntax − [source] ---- PRAGMA [database.]page_count; ---- The size of the database file should be page_count * page_size. === page_size Pragma The *page_size* pragma gets or sets the size of the database pages. Following is the simple syntax. [source] ---- PRAGMA [database.]page_size; PRAGMA [database.]page_size = bytes; ---- By default, the allowed sizes are 512, 1024, 2048, 4096, 8192, 16384, and 32768 bytes. The only way to alter the page size on an existing database is to set the page size and then immediately VACUUM the database. === parser_trace Pragma The *parser_trace* pragma controls printing the debugging state as it parses SQL commands. Following is the simple syntax. [source] ---- PRAGMA parser_trace = [true|false]; ---- By default, it is set to false but when enabled by setting it to true, the SQL parser will print its state as it parses SQL commands. === recursive_triggers Pragma The *recursive_triggers* pragma gets or sets the recursive trigger functionality. If recursive triggers are not enabled, a trigger action will not fire another trigger. Following is the simple syntax. [source] ---- PRAGMA recursive_triggers; PRAGMA recursive_triggers = [true|false]; ---- === schema_version Pragma The *schema_version* pragma gets or sets the schema version value that is stored in the database header. Following is the simple syntax. [source] ---- PRAGMA [database.]schema_version; PRAGMA [database.]schema_version = number; ---- This is a 32-bit signed integer value that keeps track of schema changes. Whenever a schema-altering command is executed (like, CREATE... or DROP...), this value is incremented. === secure_delete Pragma The *secure_delete* pragma is used to control how the content is deleted from the database. Following is the simple syntax. [source] ---- PRAGMA secure_delete; PRAGMA secure_delete = [true|false]; PRAGMA database.secure_delete; PRAGMA database.secure_delete = [true|false]; ---- The default value for the secure delete flag is normally off, but this can be changed with the SQLITE_SECURE_DELETE build option. === sql_trace Pragma The *sql_trace* pragma is used to dump SQL trace results to the screen. Following is the simple syntax. [source] ---- PRAGMA sql_trace; PRAGMA sql_trace = [true|false]; ---- SQLite must be compiled with the SQLITE_DEBUG directive for this pragma to be included. === synchronous Pragma The *synchronous* pragma gets or sets the current disk synchronization mode, which controls how aggressively SQLite will write data all the way out to physical storage. Following is the simple syntax. [source] ---- PRAGMA [database.]synchronous; PRAGMA [database.]synchronous = mode; ---- SQLite supports the following synchronization modes as listed in the table. [%autowidth] |=== |Sr.No.|Pragma Value & Description |1|*0 or OFF* No syncs at all |2|*1 or NORMAL* Sync after each sequence of critical disk operations |3|*2 or FULL* Sync after each critical disk operation |=== === temp_store Pragma The *temp_store* pragma gets or sets the storage mode used by temporary database files. Following is the simple syntax. [source] ---- PRAGMA temp_store; PRAGMA temp_store = mode; ---- SQLite supports the following storage modes. [%autowidth] |=== |Sr.No.|Pragma Value & Description |1|*0 or DEFAULT* Use compile-time default. Normally FILE. |2|*1 or FILE* Use file-based storage. |3|*2 or MEMORY* Use memory-based storage. |=== === temp_store_directory Pragma The *temp_store_directory* pragma gets or sets the location used for temporary database files. Following is the simple syntax. [source] ---- PRAGMA temp_store_directory; PRAGMA temp_store_directory = 'directory_path'; ---- === user_version Pragma The *user_version* pragma gets or sets the user-defined version value that is stored in the database header. Following is the simple syntax. [source] ---- PRAGMA [database.]user_version; PRAGMA [database.]user_version = number; ---- This is a 32-bit signed integer value, which can be set by the developer for version tracking purpose. === writable_schema Pragma The *writable_schema* pragma gets or sets the ability to modify system tables. Following is the simple syntax. [source] ---- PRAGMA writable_schema; PRAGMA writable_schema = [true|false]; ---- If this pragma is set, tables that start with sqlite_ can be created and modified, including the sqlite_master table. Be careful while using pragma because it can lead to complete database corruption. == SQLite - Constraints Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table. Following are commonly used constraints available in SQLite. . *NOT NULL Constraint* − Ensures that a column cannot have NULL value. . *DEFAULT Constraint * − Provides a default value for a column when none is specified. . *UNIQUE Constraint* − Ensures that all values in a column are different. . *PRIMARY Key* − Uniquely identifies each row/record in a database table. . *CHECK Constraint* − Ensures that all values in a column satisfies certain conditions. === NOT NULL Constraint By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column. A NULL is not the same as no data, rather, it represents unknown data. ==== Example For example, the following SQLite statement creates a new table called COMPANY and adds five columns, three of which, ID and NAME and AGE, specifies not to accept NULLs. [source] ---- CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ---- === DEFAULT Constraint The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value. ==== Example For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, SALARY column is set to 5000.00 by default, thus in case INSERT INTO statement does not provide a value for this column, then by default, this column would be set to 5000.00. [source] ---- CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL DEFAULT 50000.00 ); ---- === UNIQUE Constraint The UNIQUE Constraint prevents two records from having identical values in a particular column. In the COMPANY table, for example, you might want to prevent two or more people from having an identical age. ==== Example For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with the same age − [source] ---- CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR(50), SALARY REAL DEFAULT 50000.00 ); ---- === PRIMARY KEY Constraint The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique IDs. We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to a 'longstanding coding oversight', primary keys can be NULL in SQLite. This is not the case with other databases. A primary key is a field in a table which uniquely identifies each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a *composite key*. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s). ==== Example You already have seen various examples above where we have created COMPANY table with ID as a primary key. [source] ---- CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ---- === CHECK Constraint CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table. ==== Example For example, the following SQLite creates a new table called COMPANY and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot have any SALARY Zero. [source] ---- CREATE TABLE COMPANY3( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL CHECK(SALARY > 0) ); ---- === Dropping Constraint SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. == SQLite - JOINS SQLite *Joins* clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. SQL defines three major types of joins − . The CROSS JOIN . The INNER JOIN . The OUTER JOIN Before we proceed, let's consider two tables COMPANY and DEPARTMENT. We already have seen INSERT statements to populate COMPANY table. So just let's assume the list of records available in COMPANY table − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Another table is DEPARTMENT with the following definition − [source] ---- CREATE TABLE DEPARTMENT( ID INT PRIMARY KEY NOT NULL, DEPT CHAR(50) NOT NULL, EMP_ID INT NOT NULL ); ---- Here is the list of INSERT statements to populate DEPARTMENT table − [source] ---- INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID) VALUES (1, 'IT Billing', 1 ); INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID) VALUES (2, 'Engineering', 2 ); INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID) VALUES (3, 'Finance', 7 ); ---- Finally, we have the following list of records available in DEPARTMENT table − [source] ---- ID DEPT EMP_ID ---------- ---------- ---------- 1 IT Billing 1 2 Engineering 2 3 Finance 7 ---- === The CROSS JOIN CROSS JOIN matches every row of the first table with every row of the second table. If the input tables have x and y row, respectively, the resulting table will have x*y row. Because CROSS JOINs have the potential to generate extremely large tables, care must be taken to only use them when appropriate. Following is the syntax of CROSS JOIN − [source] ---- SELECT ... FROM table1 CROSS JOIN table2 ... ---- Based on the above tables, you can write a CROSS JOIN as follows − [source] ---- sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT; ---- The above query will produce the following result − [source] ---- EMP_ID NAME DEPT ---------- ---------- ---------- 1 Paul IT Billing 2 Paul Engineering 7 Paul Finance 1 Allen IT Billing 2 Allen Engineering 7 Allen Finance 1 Teddy IT Billing 2 Teddy Engineering 7 Teddy Finance 1 Mark IT Billing 2 Mark Engineering 7 Mark Finance 1 David IT Billing 2 David Engineering 7 David Finance 1 Kim IT Billing 2 Kim Engineering 7 Kim Finance 1 James IT Billing 2 James Engineering 7 James Finance ---- === The INNER JOIN INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows of A and B are combined into a result row. An INNER JOIN is the most common and default type of join. You can use INNER keyword optionally. Following is the syntax of INNER JOIN − [source] ---- SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression ... ---- To avoid redundancy and keep the phrasing shorter, INNER JOIN conditions can be declared with a *USING* expression. This expression specifies a list of one or more columns. [source] ---- SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ... ---- A NATURAL JOIN is similar to a *JOIN...USING*, only it automatically tests for equality between the values of every column that exists in both tables − [source] ---- SELECT ... FROM table1 NATURAL JOIN table2... ---- Based on the above tables, you can write an INNER JOIN as follows − [source] ---- sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID; ---- The above query will produce the following result − [source] ---- EMP_ID NAME DEPT ---------- ---------- ---------- 1 Paul IT Billing 2 Allen Engineering 7 James Finance ---- === The OUTER JOIN OUTER JOIN is an extension of INNER JOIN. Though SQL standard defines three types of OUTER JOINs: LEFT, RIGHT, and FULL, SQLite only supports the *LEFT OUTER JOIN*. OUTER JOINs have a condition that is identical to INNER JOINs, expressed using an ON, USING, or NATURAL keyword. The initial results table is calculated the same way. Once the primary JOIN is calculated, an OUTER JOIN will take any unjoined rows from one or both tables, pad them out with NULLs, and append them to the resulting table. Following is the syntax of LEFT OUTER JOIN − [source] ---- SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ... ---- To avoid redundancy and keep the phrasing shorter, OUTER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns. [source] ---- SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ... ---- Based on the above tables, you can write an outer join as follows − [source] ---- sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID; ---- The above query will produce the following result − [source] ---- EMP_ID NAME DEPT ---------- ---------- ---------- 1 Paul IT Billing 2 Allen Engineering Teddy Mark David Kim 7 James Finance ---- == SQLite - UNION Clause SQLite *UNION* clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length. ==== Syntax Following is the basic syntax of *UNION*. [source] ---- SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] ---- Here the given condition could be any given expression based on your requirement. ==== Example Consider the following two tables, (a) link:../sqlite/company.sql[COMPANY] table as follows − [source] ---- sqlite> select * from COMPANY; ID NAME AGE ADDRESS SALARY ---------- -------------------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- (b) Another table is link:../sqlite/department.sql[DEPARTMENT] as follows − [source] ---- ID DEPT EMP_ID ---------- -------------------- ---------- 1 IT Billing 1 2 Engineering 2 3 Finance 7 4 Engineering 3 5 Finance 4 6 Engineering 5 7 Finance 6 ---- Now let us join these two tables using SELECT statement along with UNION clause as follows − [source] ---- sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID UNION SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID; ---- This will produce the following result. [source] ---- EMP_ID NAME DEPT ---------- -------------------- ---------- 1 Paul IT Billing 2 Allen Engineering 3 Teddy Engineering 4 Mark Finance 5 David Engineering 6 Kim Finance 7 James Finance ---- === The UNION ALL Clause The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator as well. ==== Syntax Following is the basic syntax of *UNION ALL*. [source] ---- SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALL SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] ---- Here the given condition could be any given expression based on your requirement. ==== Example Now, let us join the above-mentioned two tables in our SELECT statement as follows − [source] ---- sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID UNION ALL SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID; ---- This will produce the following result. [source] ---- EMP_ID NAME DEPT ---------- -------------------- ---------- 1 Paul IT Billing 2 Allen Engineering 3 Teddy Engineering 4 Mark Finance 5 David Engineering 6 Kim Finance 7 James Finance 1 Paul IT Billing 2 Allen Engineering 3 Teddy Engineering 4 Mark Finance 5 David Engineering 6 Kim Finance 7 James Finance ---- == SQLite - NULL Values SQLite *NULL* is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. === Syntax Following is the basic syntax of using *NULL* while creating a table. [source] ---- SQLite> CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ---- Here, *NOT NULL* signifies that the column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL which means these columns could be NULL. A field with a NULL value is one that has been left blank during record creation. === Example The NULL value can cause problems when selecting data, because when comparing an unknown value to any other value, the result is always unknown and not included in the final results. Consider the following table, link:../sqlite/company.sql[COMPANY] with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Let us use UPDATE statement to set a few nullable values as NULL as follows − [source] ---- sqlite> UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7); ---- Now, COMPANY table will have the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 7 James 24 ---- Next, let us see the usage of *IS NOT NULL* operator to list down all the records where SALARY is not NULL. [source] ---- sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM COMPANY WHERE SALARY IS NOT NULL; ---- The above SQLite statement will produce the following result − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- Following is the usage of *IS NULL* operator, which will list down all the records where SALARY is NULL. [source] ---- sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM COMPANY WHERE SALARY IS NULL; ---- The above SQLite statement will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 6 Kim 22 7 James 24 ---- == SQLite - ALIAS Syntax You can rename a table or a column temporarily by giving another name, which is known as *ALIAS*. The use of table aliases means to rename a table in a particular SQLite statement. Renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQLite query. === Syntax Following is the basic syntax of *table* alias. [source] ---- SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; ---- Following is the basic syntax of *column* alias. [source] ---- SELECT column_name AS alias_name FROM table_name WHERE [condition]; ---- === Example Consider the following two tables, (a) link:../sqlite/company.sql[COMPANY] table is as follows − [source] ---- sqlite> select * from COMPANY; ID NAME AGE ADDRESS SALARY ---------- -------------------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- (b) Another table is link:../sqlite/department.sql[DEPARTMENT] as follows − [source] ---- ID DEPT EMP_ID ---------- -------------------- ---------- 1 IT Billing 1 2 Engineering 2 3 Finance 7 4 Engineering 3 5 Finance 4 6 Engineering 5 7 Finance 6 ---- Now, following is the usage of *TABLE ALIAS* where we use C and D as aliases for COMPANY and DEPARTMENT tables respectively − [source] ---- sqlite> SELECT C.ID, C.NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID; ---- The above SQLite statement will produce the following result − [source] ---- ID NAME AGE DEPT ---------- ---------- ---------- ---------- 1 Paul 32 IT Billing 2 Allen 25 Engineering 3 Teddy 23 Engineering 4 Mark 25 Finance 5 David 27 Engineering 6 Kim 22 Finance 7 James 24 Finance ---- Consider an example for the usage of *COLUMN ALIAS* where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column. [source] ---- sqlite> SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID; ---- The above SQLite statement will produce the following result − [source] ---- COMPANY_ID COMPANY_NAME AGE DEPT ---------- ------------ ---------- ---------- 1 Paul 32 IT Billing 2 Allen 25 Engineering 3 Teddy 23 Engineering 4 Mark 25 Finance 5 David 27 Engineering 6 Kim 22 Finance 7 James 24 Finance ---- == SQLite - Triggers SQLite *Triggers* are database callback functions, which are automatically performed/invoked when a specified database event occurs. Following are the important points about SQLite triggers − . SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table. . At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional. . Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form *NEW.column-name* and *OLD.column-name*, where column-name is the name of a column from the table that the trigger is associated with. . If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows. . The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row. . Triggers are automatically dropped when the table that they are associated with is dropped. . The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just *tablename* not *database.tablename*. . A special SQL function RAISE() may be used within a trigger-program to raise an exception. ==== Syntax Following is the basic syntax of creating a *trigger*. [source] ---- CREATE TRIGGER trigger_name [BEFORE|AFTER] event_name ON table_name BEGIN -- Trigger logic goes here.... END; ---- Here, *event_name* could be INSERT, DELETE, and UPDATE database operation on the mentioned table *table_name*. You can optionally specify FOR EACH ROW after table name. Following is the syntax for creating a trigger on an UPDATE operation on one or more specified columns of a table. [source] ---- CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name ON table_name BEGIN -- Trigger logic goes here.... END; ---- ==== Example Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we create newly as follows (Drop COMPANY table if you already have it). [source] ---- sqlite> CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ---- To keep audit trial, we will create a new table called AUDIT where the log messages will be inserted, whenever there is an entry in COMPANY table for a new record. [source] ---- sqlite> CREATE TABLE AUDIT( EMP_ID INT NOT NULL, ENTRY_DATE TEXT NOT NULL ); ---- Here, ID is the AUDIT record ID, and EMP_ID is the ID which will come from COMPANY table and DATE will keep timestamp when the record will be created in COMPANY table. Now let's create a trigger on COMPANY table as follows − [source] ---- sqlite> CREATE TRIGGER audit_log AFTER INSERT ON COMPANY BEGIN INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now')); END; ---- Now, we will start actual work, Let's start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. Create one record in COMPANY table as follows − [source] ---- sqlite> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); ---- This will create one record in COMPANY table, which is as follows − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 ---- Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation in COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements. [source] ---- EMP_ID ENTRY_DATE ---------- ------------------- 1 2013-04-05 06:26:00 ---- === Listing Triggers You can list down all the triggers from *sqlite_master* table as follows − [source] ---- sqlite> SELECT name FROM sqlite_master WHERE type = 'trigger'; ---- The above SQLite statement will list down only one entry as follows − [source] ---- name
audit_log
If you want to list down triggers on a particular table, then use AND clause with table name as follows − [source]
sqlite> SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'COMPANY';
The above SQLite statement will also list down only one entry as follows − [source]
name
audit_log ---- === Dropping Triggers Following is the DROP command, which can be used to drop an existing trigger. [source] ---- sqlite> DROP TRIGGER trigger_name; ---- == SQLite - Indexes Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an *index* is a pointer to data in a table. An index in a database is very similar to an index in the back of a book. For example, if you want to reference all pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers. An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data. Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in an ascending or descending order. Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there's an index. === The CREATE INDEX Command Following is the basic syntax of *CREATE INDEX*. [source] ---- CREATE INDEX index_name ON table_name; ---- ==== Single-Column Indexes A single-column index is one that is created based on only one table column. The basic syntax is as follows − [source] ---- CREATE INDEX index_name ON table_name (column_name); ---- ==== Unique Indexes Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows − [source] ---- CREATE UNIQUE INDEX index_name on table_name (column_name); ---- ==== Composite Indexes A composite index is an index on two or more columns of a table. The basic syntax is as follows − [source] ---- CREATE INDEX index_name on table_name (column1, column2); ---- Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions. Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice. ==== Implicit Indexes Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints. *Example* Following is an example where we will create an index in link:../sqlite/company.sql[COMPANY] table for salary column − [source] ---- sqlite> CREATE INDEX salary_index ON COMPANY (salary); ---- Now, let's list down all the indices available in COMPANY table using *.indices* command as follows − [source] ---- sqlite> .indices COMPANY ---- This will produce the following result, where sqlite_autoindex_COMPANY_1 is an implicit index which got created when the table itself was created. [source] ---- salary_index sqlite_autoindex_COMPANY_1 ---- You can list down all the indexes database wide as follows − [source] ---- sqlite> SELECT * FROM sqlite_master WHERE type = 'index'; ---- === The DROP INDEX Command An index can be dropped using SQLite *DROP* command. Care should be taken when dropping an index because performance may be slowed or improved. Following is the basic syntax is as follows − [source] ---- DROP INDEX index_name; ---- You can use the following statement to delete previously created index. [source] ---- sqlite> DROP INDEX salary_index; ---- ==== When Should Indexes Be Avoided? Although indexes are intended to enhance the performance of a database, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered. Indexes should not be used in − . Small tables. . Tables that have frequent, large batch update or insert operations. . Columns that contain a high number of NULL values. . Columns that are frequently manipulated. == SQLite - INDEXED BY Clause The "INDEXED BY index-name" clause specifies that the named index must be used in order to look up values on the preceding table. If index-name does not exist or cannot be used for the query, then the preparation of the SQLite statement fails. The "NOT INDEXED" clause specifies that no index shall be used when accessing the preceding table, including implied indices created by UNIQUE and PRIMARY KEY constraints. However, the INTEGER PRIMARY KEY can still be used to look up entries even when "NOT INDEXED" is specified. === Syntax Following is the syntax for INDEXED BY clause and it can be used with DELETE, UPDATE or SELECT statement. [source] ---- SELECT|DELETE|UPDATE column1, column2... INDEXED BY (index_name) table_name WHERE (CONDITION); ---- === Example Consider table link:../sqlite/company.sql[COMPANY] We will create an index and use it for performing INDEXED BY operation. [source] ---- sqlite> CREATE INDEX salary_index ON COMPANY(salary); sqlite> ---- Now selecting the data from table COMPANY you can use INDEXED BY clause as follows − [source] ---- sqlite> SELECT * FROM COMPANY INDEXED BY salary_index WHERE salary > 5000; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 7 James 24 Houston 10000.0 2 Allen 25 Texas 15000.0 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- == SQLite - ALTER TABLE Command SQLite *ALTER TABLE* command modifies an existing table without performing a full dump and reload of the data. You can rename a table using ALTER TABLE statement and additional columns can be added in an existing table using ALTER TABLE statement. There is no other operation supported by ALTER TABLE command in SQLite except renaming a table and adding a column in an existing table. === Syntax Following is the basic syntax of *ALTER TABLE* to RENAME an existing table. [source] ---- ALTER TABLE database_name.table_name RENAME TO new_table_name; ---- Following is the basic syntax of *ALTER TABLE* to add a new column in an existing table. [source] ---- ALTER TABLE database_name.table_name ADD COLUMN column_def...; ---- === Example Consider the link:../sqlite/company.sql[COMPANY] table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Now, let's try to rename this table using ALTER TABLE statement as follows − [source] ---- sqlite> ALTER TABLE COMPANY RENAME TO OLD_COMPANY; ---- The above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column in OLD_COMPANY table as follows − [source] ---- sqlite> ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1); ---- COMPANY table is now changed and following will be the output from SELECT statement. [source] ---- ID NAME AGE ADDRESS SALARY SEX ---------- ---------- ---------- ---------- ---------- --- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- It should be noted that newly added column is filled with NULL values. == SQLite - TRUNCATE TABLE Command Unfortunately, we do not have TRUNCATE TABLE command in SQLite but you can use SQLite *DELETE * command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop the complete table and re-create it once again. === Syntax Following is the basic syntax of DELETE command. [source] ---- sqlite> DELETE FROM table_name; ---- Following is the basic syntax of DROP TABLE. [source] ---- sqlite> DROP TABLE table_name; ---- If you are using DELETE TABLE command to delete all the records, it is recommended to use *VACUUM* command to clear unused space. === Example Consider link:../sqlite/company.sql[COMPANY] table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is the example to truncate the above table − [source] ---- SQLite> DELETE FROM COMPANY; SQLite> VACUUM; ---- Now, COMPANY table is truncated completely and nothing will be the output from SELECT statement. == SQLite - Views A view is nothing more than a SQLite statement that is stored in the database with an associated name. It is actually a composition of a table in the form of a predefined SQLite query. A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables which depends on the written SQLite query to create a view. Views which are kind of virtual tables, allow the users to − . Structure data in a way that users or classes of users find natural or intuitive. . Restrict access to the data such that a user can only see limited data instead of a complete table. . Summarize data from various tables, which can be used to generate reports. SQLite views are read-only and thus you may not be able to execute a DELETE, INSERT or UPDATE statement on a view. However, you can create a trigger on a view that fires on an attempt to DELETE, INSERT, or UPDATE a view and do what you need in the body of the trigger. === Creating Views SQLite views are created using the *CREATE VIEW* statement. SQLite views can be created from a single table, multiple tables, or another view. Following is the basic CREATE VIEW syntax. [source] ---- CREATE [TEMP | TEMPORARY] VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition]; ---- You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temp database. ==== Example Consider link:../sqlite/company.sql[COMPANY] table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Following is an example to create a view from COMPANY table. This view will be used to have only a few columns from COMPANY table. [source] ---- sqlite> CREATE VIEW COMPANY_VIEW AS SELECT ID, NAME, AGE FROM COMPANY; ---- You can now query COMPANY_VIEW in a similar way as you query an actual table. Following is an example − [source] ---- sqlite> SELECT * FROM COMPANY_VIEW; ---- This will produce the following result. [source] ---- ID NAME AGE ---------- ---------- ---------- 1 Paul 32 2 Allen 25 3 Teddy 23 4 Mark 25 5 David 27 6 Kim 22 7 James 24 ---- === Dropping Views To drop a view, simply use the DROP VIEW statement with the *view_name*. The basic DROP VIEW syntax is as follows − [source] ---- sqlite> DROP VIEW view_name; ---- The following command will delete COMPANY_VIEW view, which we created in the last section. [source] ---- sqlite> DROP VIEW COMPANY_VIEW; ---- == SQLite - Transactions A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. A transaction is the propagation of one or more changes to the database. For example, if you are creating, updating, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors. Practically, you will club many SQLite queries into a group and you will execute all of them together as part of a transaction. === Properties of Transactions Transactions have the following four standard properties, usually referred to by the acronym ACID. . *Atomicity* − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. . *Consistency* − Ensures that the database properly changes states upon a successfully committed transaction. . *Isolation* − Enables transactions to operate independently of and transparent to each other. . *Durability* − Ensures that the result or effect of a committed transaction persists in case of a system failure. === Transaction Control Following are the following commands used to control transactions: . *BEGIN TRANSACTION* − To start a transaction. . *COMMIT* − To save the changes, alternatively you can use *END TRANSACTION* command. . *ROLLBACK* − To rollback the changes. Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database. ==== BEGIN TRANSACTION Command Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. However, a transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the simple syntax to start a transaction. [source] ---- BEGIN; or BEGIN TRANSACTION; ---- ==== COMMIT Command COMMIT command is the transactional command used to save changes invoked by a transaction to the database. COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command. Following is the syntax for COMMIT command. [source] ---- COMMIT; or END TRANSACTION; ---- ==== ROLLBACK Command ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. Following is the syntax for ROLLBACK command. [source] ---- ROLLBACK; ---- *Example* Consider link:../sqlite/company.sql[COMPANY] table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Now, let's start a transaction and delete records from the table having age = 25. Then, use ROLLBACK command to undo all the changes. [source] ---- sqlite> BEGIN; sqlite> DELETE FROM COMPANY WHERE AGE = 25; sqlite> ROLLBACK; ---- Now, if you check COMPANY table, it still has the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Let's start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes. [source] ---- sqlite> BEGIN; sqlite> DELETE FROM COMPANY WHERE AGE = 25; sqlite> COMMIT; ---- If you now check COMPANY table is still has the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- == SQLite - Subqueries A Subquery or Inner query or Nested query is a query within another SQLite query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators such as =, <, >, >=, <=, IN, BETWEEN, etc. There are a few rules that subqueries must follow − . Subqueries must be enclosed within parentheses. . A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. . An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery. . Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator. . BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery. === Subqueries with SELECT Statement Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows − [source] ---- SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE]) ---- ==== Example Consider link:../sqlite/company.sql[COMPANY] table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Now, let us check the following sub-query with SELECT statement. [source] ---- sqlite> SELECT * FROM COMPANY WHERE ID IN (SELECT ID FROM COMPANY WHERE SALARY > 45000) ; ---- This will produce the following result. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 ---- === Subqueries with INSERT Statement Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions. Following is the basic syntax is as follows − [source] ---- INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ] ---- ==== Example Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. To copy the complete COMPANY table into COMPANY_BKP, following is the syntax − [source] ---- sqlite> INSERT INTO COMPANY_BKP SELECT * FROM COMPANY WHERE ID IN (SELECT ID FROM COMPANY) ; ---- === Subqueries with UPDATE Statement The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement. Following is the basic syntax is as follows − [source] ---- UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] ---- ==== Example Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table. Following example updates SALARY by 0.50 times in COMPANY table for all the customers, whose AGE is greater than or equal to 27. [source] ---- sqlite> UPDATE COMPANY SET SALARY = SALARY * 0.50 WHERE AGE IN (SELECT AGE FROM COMPANY_BKP WHERE AGE >= 27 ); ---- This would impact two rows and finally COMPANY table would have the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 10000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 42500.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- === Subqueries with DELETE Statement Subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above. Following is the basic syntax is as follows − [source] ---- DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] ---- ==== Example Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table. Following example deletes records from COMPANY table for all the customers whose AGE is greater than or equal to 27. [source] ---- sqlite> DELETE FROM COMPANY WHERE AGE IN (SELECT AGE FROM COMPANY_BKP WHERE AGE > 27 ); ---- This will impact two rows and finally COMPANY table will have the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 42500.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- == SQLite - AUTOINCREMENT SQLite *AUTOINCREMENT* is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using *AUTOINCREMENT* keyword when creating a table with specific column name to auto increment. The keyword *AUTOINCREMENT* can be used with INTEGER field only. === Syntax The basic usage of *AUTOINCREMENT* keyword is as follows − [source] ---- CREATE TABLE table_name( column1 INTEGER AUTOINCREMENT, column2 datatype, column3 datatype, ..... columnN datatype, ); ---- === Example Consider COMPANY table to be created as follows − [source] ---- sqlite> CREATE TABLE COMPANY( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ---- Now, insert the following records into table COMPANY − [source] ---- INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'David', 27, 'Texas', 85000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Kim', 22, 'South-Hall', 45000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'James', 24, 'Houston', 10000.00 ); ---- This will insert 7 tuples into the table COMPANY and COMPANY will have the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- == SQLite - Injection If you take user input through a webpage and insert it into a SQLite database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. In this chapter, you will learn how to help prevent this from happening and help you secure your scripts and SQLite statements. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQLite statement that you will unknowingly run on your database. Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching. In the following example, the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars - modify these rules as needed. [source] ---- if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)){ $db = new SQLiteDatabase('filename'); $result = @$db->query("SELECT * FROM users WHERE username = $matches[0]"); } else { echo "username not accepted"; } ---- To demonstrate the problem, consider this excerpt − [source] ---- $name = "Qadir'; DELETE FROM users;"; @$db->query("SELECT * FROM users WHERE username = '{$name}'"); ---- The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. Under normal circumstances, *$name* would only contain alphanumeric characters and perhaps spaces, such as the string ilia. However in this case, by appending an entirely new query to $name, the call to the database turns into a disaster: the injected DELETE query removes all records from users. There are databases interfaces which do not permit query stacking or executing multiple queries in a single function call. If you try to stack queries, the call fails but SQLite and PostgreSQL, happily perform stacked queries, executing all of the queries provided in one string and creating a serious security problem. === Preventing SQL Injection You can handle all escape characters smartly in scripting languages like PERL and PHP. Programming language PHP provides the function *string sqlite_escape_string()* to escape input characters that are special to SQLite. [source] ---- if (get_magic_quotes_gpc()) { $name = sqlite_escape_string($name); } $result = @$db->query("SELECT * FROM users WHERE username = '{$name}'"); ---- Although the encoding makes it safe to insert the data, it will render simple text comparisons and *LIKE* clauses in your queries unusable for the columns that contain the binary data. *Note* − *addslashes()* should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data. == SQLite - EXPLAIN SQLite statement can be preceded by the keyword "EXPLAIN" or by the phrase "EXPLAIN QUERY PLAN" used for describing the details of a table. Either modification causes the SQLite statement to behave as a query and to return information about how the SQLite statement would have operated if the EXPLAIN keyword or phrase had been omitted. . The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive analysis and troubleshooting only. . The details of the output format are subject to change from one release of SQLite to the next. . Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is variable and only partially documented. === Syntax syntax for *EXPLAIN* is as follows − [source] ---- EXPLAIN [SQLite Query] ---- syntax for *EXPLAIN QUERY PLAN* is as follows − [source] ---- EXPLAIN QUERY PLAN [SQLite Query] ---- === Example Consider link:../sqlite/company.sql[COMPANY] table with the following records − [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- Now, let us check the following sub-query with SELECT statement − [source] ---- sqlite> EXPLAIN SELECT * FROM COMPANY WHERE Salary >= 20000; ---- This will produce the following result. [source] ---- addr opcode p1 p2 p3 ---------- ---------- ---------- ---------- ---------- 0 Goto 0 19 1 Integer 0 0 2 OpenRead 0 8 3 SetNumColu 0 5 4 Rewind 0 17 5 Column 0 4 6 RealAffini 0 0 7 Integer 20000 0 8 Lt 357 16 collseq(BI 9 Rowid 0 0 10 Column 0 1 11 Column 0 2 12 Column 0 3 13 Column 0 4 14 RealAffini 0 0 15 Callback 5 0 16 Next 0 5 17 Close 0 0 18 Halt 0 0 19 Transactio 0 0 20 VerifyCook 0 38 21 Goto 0 1 22 Noop 0 0 ---- Now, let us check the following *Explain Query Plan * with SELECT statement − [source] ---- SQLite> EXPLAIN QUERY PLAN SELECT * FROM COMPANY WHERE Salary >= 20000; order from detail ---------- ---------- ------------- 0 0 TABLE COMPANY ---- == SQLite - VACUUM VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure. VACUUM command may change the ROWID of entries in tables that do not have an explicit INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible to VACUUM an attached database file. VACUUM command will fail if there is an active transaction. VACUUM command is a no-op for in-memory databases. As the VACUUM command rebuilds the database file from scratch, VACUUM can also be used to modify many database-specific configuration parameters. === Manual VACUUM Following is a simple syntax to issue a VACUUM command for the whole database from command prompt − [source] ---- $sqlite3 database_name "VACUUM;" ---- You can run VACUUM from SQLite prompt as well as follows − [source] ---- sqlite> VACUUM; ---- You can also run VACUUM on a particular table as follows − [source] ---- sqlite> VACUUM table_name; ---- === Auto-VACCUM SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end of the database thereby reducing the database size. By doing so it can significantly fragment the database while VACUUM ensures defragmentation. Hence, Auto-VACUUM just keeps the database small. You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt − [source] ---- sqlite> PRAGMA auto_vacuum = NONE; -- 0 means disable auto vacuum sqlite> PRAGMA auto_vacuum = FULL; -- 1 means enable full auto vacuum sqlite> PRAGMA auto_vacuum = INCREMENTAL; -- 2 means enable incremental vacuum ---- You can run the following command from the command prompt to check the auto-vacuum setting − [source] ---- $sqlite3 database_name "PRAGMA auto_vacuum;" ---- == SQLite - Date & Time SQLite supports five date and time functions as follows − [%autowidth] |=== |Sr.No.|Function|Example |1|date(timestring, modifiers...)|This returns the date in this format: YYYY-MM-DD |2|time(timestring, modifiers...)|This returns the time as HH:MM:SS |3|datetime(timestring, modifiers...)|This returns YYYY-MM-DD HH:MM:SS |4|julianday(timestring, modifiers...)|This returns the number of days since noon in Greenwich on November 24, 4714 B.C. |5|strftime(timestring, modifiers...)|This returns the date formatted according to the format string specified as the first argument formatted as per formatters explained below. |=== All the above five date and time functions take a time string as an argument. The time string is followed by zero or more modifiers. The strftime() function also takes a format string as its first argument. Following section will give you detail on different types of time strings and modifiers. === Time Strings A time string can be in any of the following formats − [%autowidth] |=== |Sr.No.|Time String|Example |1|YYYY-MM-DD|2010-12-30 |2|YYYY-MM-DD HH:MM|2010-12-30 12:10 |3|YYYY-MM-DD HH:MM:SS.SSS|2010-12-30 12:10:04.100 |4|MM-DD-YYYY HH:MM|30-12-2010 12:10 |5|HH:MM|12:10 |6|YYYY-MM-DD*T*HH:MM|2010-12-30 12:10 |7|HH:MM:SS|12:10:01 |8|YYYYMMDD HHMMSS|20101230 121001 |9|now|2013-05-07 |=== You can use the "T" as a literal character separating the date and the time. === Modifiers The time string can be followed by zero or more modifiers that will alter date and/or time returned by any of the above five functions. Modifiers are applied from the left to right. Following modifers are available in SQLite − . NNN days . NNN hours . NNN minutes . NNN.NNNN seconds . NNN months . NNN years . start of month . start of year . start of day . weekday N . unixepoch . localtime . utc === Formatters SQLite provides a very handy function *strftime()* to format any date and time. You can use the following substitutions to format your date and time. [%autowidth] |=== |Substitution|Description |%d|Day of month, 01-31 |%f|Fractional seconds, SS.SSS |%H|Hour, 00-23 |%j|Day of year, 001-366 |%J|Julian day number, DDDD.DDDD |%m|Month, 00-12 |%M|Minute, 00-59 |%s|Seconds since 1970-01-01 |%S|Seconds, 00-59 |%w|Day of week, 0-6 (0 is Sunday) |%W|Week of year, 01-53 |%Y|Year, YYYY |%%|% symbol |=== ==== Examples Let's try various examples now using SQLite prompt. Following command computes the current date. [source] ---- sqlite> SELECT date('now'); 2013-05-07 ---- Following command computes the last day of the current month. [source] ---- sqlite> SELECT date('now','start of month','+1 month','-1 day'); 2013-05-31 ---- Following command computes the date and time for a given UNIX timestamp 1092941466. [source] ---- sqlite> SELECT datetime(1092941466, 'unixepoch'); 2004-08-19 18:51:06 ---- Following command computes the date and time for a given UNIX timestamp 1092941466 and compensate for your local timezone. [source] ---- sqlite> SELECT datetime(1092941466, 'unixepoch', 'localtime'); 2004-08-19 13:51:06 ---- Following command computes the current UNIX timestamp. [source] ---- sqlite> SELECT strftime('%s','now'); 1393348134 ---- Following command computes the number of days since the signing of the US Declaration of Independence. [source] ---- sqlite> SELECT julianday('now') - julianday('1776-07-04'); 86798.7094695023 ---- Following command computes the number of seconds since a particular moment in 2004. [source] ---- sqlite> SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56'); 295001572 ---- Following command computes the date of the first Tuesday in October for the current year. [source] ---- sqlite> SELECT date('now','start of year','+9 months','weekday 2'); 2013-10-01 ---- Following command computes the time since the UNIX epoch in seconds (like strftime('%s','now') except includes fractional part). [source] ---- sqlite> SELECT (julianday('now') - 2440587.5)*86400.0; 1367926077.12598 ---- To convert between UTC and local time values when formatting a date, use the utc or localtime modifiers as follows − [source] ---- sqlite> SELECT time('12:00', 'localtime'); 05:00:00 ---- [source] ---- sqlite> SELECT time('12:00', 'utc'); 19:00:00 ---- == SQLite - Useful Functions SQLite has many built-in functions to perform processing on string or numeric data. Following is the list of few useful SQLite built-in functions and all are case in-sensitive which means you can use these functions either in lower-case form or in upper-case or in mixed form. For more details, you can check official documentation for SQLite. [%autowidth] |=== |Sr.No.|Function & Description |1|*SQLite COUNT Function* SQLite COUNT aggregate function is used to count the number of rows in a database table. |2|*SQLite MAX Function * SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. |3|*SQLite MIN Function* SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. |4|*SQLite AVG Function * SQLite AVG aggregate function selects the average value for certain table column. |5|*SQLite SUM Function* SQLite SUM aggregate function allows selecting the total for a numeric column. |6|*SQLite RANDOM Function* SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. |7|*SQLite ABS Function* SQLite ABS function returns the absolute value of the numeric argument. |8|*SQLite UPPER Function* SQLite UPPER function converts a string into upper-case letters. |9|*SQLite LOWER Function* SQLite LOWER function converts a string into lower-case letters. |10|*SQLite LENGTH Function* SQLite LENGTH function returns the length of a string. |11|*SQLite sqlite_version Function* SQLite sqlite_version function returns the version of the SQLite library. |=== Before we start giving examples on the above-mentioned functions, consider COMPANY table with the following records. [source] ---- ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 ---- === SQLite COUNT Function SQLite COUNT aggregate function is used to count the number of rows in a database table. Following is an example − [source] ---- sqlite> SELECT count(*) FROM COMPANY; ---- The above SQLite SQL statement will produce the following. [source] ---- count(*)
7
=== SQLite MAX Function SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. Following is an example − [source]
sqlite> SELECT max(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following. [source]
max(salary)
85000.0
=== SQLite MIN Function SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. Following is an example − [source]
sqlite> SELECT min(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following. [source]
min(salary)
10000.0
=== SQLite AVG Function SQLite AVG aggregate function selects the average value for a certain table column. Following is an the example − [source]
sqlite> SELECT avg(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following. [source]
avg(salary)
37142.8571428572 ---- === SQLite SUM Function SQLite SUM aggregate function allows selecting the total for a numeric column. Following is an example − [source] ---- sqlite> SELECT sum(salary) FROM COMPANY; ---- The above SQLite SQL statement will produce the following. [source] ---- sum(salary) ----------- 260000.0 ---- === SQLite RANDOM Function SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. Following is an example − [source] ---- sqlite> SELECT random() AS Random; ---- The above SQLite SQL statement will produce the following. [source] ---- Random ------------------- 5876796417670984050 ---- === SQLite ABS Function SQLite ABS function returns the absolute value of the numeric argument. Following is an example − [source] ---- sqlite> SELECT abs(5), abs(-15), abs(NULL), abs(0), abs("ABC"); ---- The above SQLite SQL statement will produce the following. [source] ---- abs(5) abs(-15) abs(NULL) abs(0) abs("ABC") ---------- ---------- ---------- ---------- ---------- 5 15 0 0.0 ---- === SQLite UPPER Function SQLite UPPER function converts a string into upper-case letters. Following is an example − [source] ---- sqlite> SELECT upper(name) FROM COMPANY; ---- The above SQLite SQL statement will produce the following. [source] ---- upper(name) ----------- PAUL ALLEN TEDDY MARK DAVID KIM JAMES ---- === SQLite LOWER Function SQLite LOWER function converts a string into lower-case letters. Following is an example − [source] ---- sqlite> SELECT lower(name) FROM COMPANY; ---- The above SQLite SQL statement will produce the following. [source] ---- lower(name) ----------- paul allen teddy mark david kim james ---- === SQLite LENGTH Function SQLite LENGTH function returns the length of a string. Following is an example − [source] ---- sqlite> SELECT name, length(name) FROM COMPANY; ---- The above SQLite SQL statement will produce the following. [source] ---- NAME length(name) ---------- ------------ Paul 4 Allen 5 Teddy 5 Mark 4 David 5 Kim 3 James 5 ---- === SQLite sqlite_version Function SQLite sqlite_version function returns the version of the SQLite library. Following is an example − [source] ---- sqlite> SELECT sqlite_version() AS 'SQLite Version'; ---- The above SQLite SQL statement will produce the following. [source] ---- SQLite Version -------------- 3.6.20 ---- == SQLite - C/C++ In this chapter, you will learn how to use SQLite in C/C++ programs. ==== Installation Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process. === C/C++ Interface APIs Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation. [%autowidth] |=== |Sr.No.|API & Description |1|*sqlite3_open(const char *filename, sqlite3 **ppDb)* This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines. If the filename argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session. If the filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name. |2|*sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)* This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command. Here, the first argument sqlite3 is an open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be returned to capture any error raised by the routine. SQLite3_exec() routine parses and executes every command given in the *sql* argument until it reaches the end of the string or encounters an error. |3|*sqlite3_close(sqlite3*)* This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection. If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements. |=== === Connect To Database Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. [source] ---- #include <stdio.h> #include <sqlite3.h> int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } sqlite3_close(db); } ---- Now, let's compile and run the above program to create our database *test.db* in the current directory. You can change your path as per your requirement. [source] ---- $gcc test.c -l sqlite3 $./a.out Opened database successfully ---- If you are going to use C++ source code, then you can compile your code as follows − [source] ---- $g++ test.c -l sqlite3 ---- Here, we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the following result. [source] ---- -rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out -rw-r--r--. 1 root root 323 May 8 02:05 test.c -rw-r--r--. 1 root root 0 May 8 02:06 test.db ---- === Create a Table Following C code segment will be used to create a table in the previously created database − [source] ---- #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stdout, "Opened database successfully\n"); } /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" \ "ID INT PRIMARY KEY NOT NULL," \ "NAME TEXT NOT NULL," \ "AGE INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Table created successfully\n"); } sqlite3_close(db); return 0; } ---- When the above program is compiled and executed, it will create COMPANY table in your test.db and the final listing of the file will be as follows − [source] ---- -rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out -rw-r--r--. 1 root root 1207 May 8 02:31 test.c -rw-r--r--. 1 root root 3072 May 8 02:31 test.db ---- === INSERT Operation Following C code segment shows how you can create records in COMPANY table created in the above example − [source] ---- #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Records created successfully\n"); } sqlite3_close(db); return 0; } ---- When the above program is compiled and executed, it will create the given records in COMPANY table and will display the following two lines − [source] ---- Opened database successfully Records created successfully ---- === SELECT Operation Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration − [source] ---- typedef int (*sqlite3_callback)( void*, /* Data provided in the 4th argument of sqlite3_exec() */ int, /* The number of columns in row */ char**, /* An array of strings representing fields in the row */ char** /* An array of strings representing column names */ ); ---- If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument. Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example − [source] ---- #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } ---- When the above program is compiled and executed, it will produce the following result. [source] ---- Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- === UPDATE Operation Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from the COMPANY table. [source] ---- #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create merged SQL statement */ sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \ "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } ---- When the above program is compiled and executed, it will produce the following result. [source] ---- Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- === DELETE Operation Following C code segment shows how you can use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table. [source] ---- #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName) { int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create merged SQL statement */ sql = "DELETE from COMPANY where ID=2; " \ "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } ---- When the above program is compiled and executed, it will produce the following result. [source] ---- Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- == SQLite - Java In this chapter, you will learn how to use SQLite in Java programs. === Installation Before you start using SQLite in our Java programs, you need to make sure that you have SQLite JDBC Driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up SQLite JDBC driver. . Download latest version of sqlite-jdbc-(VERSION).jar from link:http://www.java2s.com/Code/Jar/s/Downloadsqlitejdbc372jar.html[sqlite-jdbc] repository. . Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples. Following section assumes you have little knowledge about Java JDBC concepts. If you don't, then it is suggested to spent half an hour with link:../jdbc/jdbc-create-database.html[JDBC Tutorial] to become comfortable with the concepts explained below. === Connect to Database Following Java programs shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. [source] ---- import java.sql.*; public class SQLiteJDBC { public static void main( String args[] ) { Connection c = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Opened database successfully"); } } ---- Now, let's compile and run the above program to create our database *test.db* in the current directory. You can change your path as per your requirement. We are assuming the current version of JDBC driver sqlite-jdbc-3.7.2.jar is available in the current path. [source] ---- $javac SQLiteJDBC.java $java -classpath ".:sqlite-jdbc-3.7.2.jar" SQLiteJDBC Open database successfully ---- If you are going to use Windows machine, then you can compile and run your code as follows − [source] ---- $javac SQLiteJDBC.java $java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC Opened database successfully ---- === Create a Table Following Java program will be used to create a table in the previously created database. [source] ---- import java.sql.*; public class SQLiteJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "CREATE TABLE COMPANY " + "(ID INT PRIMARY KEY NOT NULL," + " NAME TEXT NOT NULL, " + " AGE INT NOT NULL, " + " ADDRESS CHAR(50), " + " SALARY REAL)"; stmt.executeUpdate(sql); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Table created successfully"); } } ---- When the above program is compiled and executed, it will create COMPANY table in your *test.db* and final listing of the file will be as follows − [source] ---- -rw-r--r--. 1 root root 3201128 Jan 22 19:04 sqlite-jdbc-3.7.2.jar -rw-r--r--. 1 root root 1506 May 8 05:43 SQLiteJDBC.class -rw-r--r--. 1 root root 832 May 8 05:42 SQLiteJDBC.java -rw-r--r--. 1 root root 3072 May 8 05:43 test.db ---- === INSERT Operation Following Java program shows how to create records in the COMPANY table created in above example. [source] ---- import java.sql.*; public class SQLiteJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (1, 'Paul', 32, 'California', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Records created successfully"); } } ---- When above program is compiled and executed, it will create given records in COMPANY table and will display following two line − [source] ---- Opened database successfully Records created successfully ---- === SELECT Operation Following Java program shows how to fetch and display records from the COMPANY table created in the above example. [source] ---- import java.sql.*; public class SQLiteJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } } ---- When the above program is compiled and executed, it will produce the following result. [source] ---- Opened database successfully ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- === UPDATE Operation Following Java code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table. [source] ---- import java.sql.*; public class SQLiteJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;"; stmt.executeUpdate(sql); c.commit(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } } ---- When the above program is compiled and executed, it will produce the following result. [source] ---- Opened database successfully ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- === DELETE Operation Following Java code shows how to use use DELETE statement to delete any record and then fetch and display the remaining records from the our COMPANY table. [source] ---- import java.sql.*; public class SQLiteJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:test.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "DELETE from COMPANY where ID=2;"; stmt.executeUpdate(sql); c.commit(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); } } ---- When the above program is compiled and executed, it will produce the following result. [source] ---- Opened database successfully ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- == SQLite - PHP In this chapter, you will learn how to use SQLite in PHP programs. === Installation SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using *--without-sqlite3* at compile time. Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0. For detailed installation instructions, kindly check our PHP tutorial and its official website. === PHP Interface APIs Following are important PHP routines which can suffice your requirement to work with SQLite database from your PHP program. If you are looking for a more sophisticated application, then you can look into PHP official documentation. [%autowidth] |=== |Sr.No.|API & Description |1|*public void SQLite3::open ( filename, flags, encryption_key )* Opens SQLite 3 Database. If the build includes encryption, then it will attempt to use the key. If the filename is given as *':memory:'*, SQLite3::open() will create an in-memory database in RAM that lasts only for the duration of the session. If the filename is actual device file name, SQLite3::open() attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created. Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE. |2|*public bool SQLite3::exec ( string $query )* This routine provides a quick, easy way to execute SQL commands provided by sql argument, which can consist of more than one SQL command. This routine is used to execute a result-less query against a given database. |3|*public SQLite3Result SQLite3::query ( string $query )* This routine executes an SQL query, returning an *SQLite3Result* object if the query returns results. |4|*public int SQLite3::lastErrorCode ( void )* This routine returns the numeric result code of the most recent failed SQLite request. |5|*public string SQLite3::lastErrorMsg ( void )* This routine returns English text describing the most recent failed SQLite request. |6|*public int SQLite3::changes ( void )* This routine returns the number of database rows that were updated, inserted, or deleted by the most recent SQL statement. |7|*public bool SQLite3::close ( void )* This routine closes a database connection previously opened by a call to SQLite3::open(). |8|*public string SQLite3::escapeString ( string $value )* This routine returns a string that has been properly escaped for safe inclusion in an SQL statement. |=== === Connect to Database Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned. [source] ---- <?php class MyDB extends SQLite3 { function __construct() { $this->open('test.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo "Opened database successfully\n"; } ?> ---- Now, let's run the above program to create our database *test.db* in the current directory. You can change your path as per your requirement. If the database is successfully created, then it will display the following message − [source] ---- Open database successfully ---- === Create a Table Following PHP program will be used to create a table in the previously created database. [source] ---- <?php class MyDB extends SQLite3 { function __construct() { $this->open('test.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo "Opened database successfully\n"; } $sql =<<<EOF CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL); EOF; $ret = $db->exec($sql); if(!$ret){ echo $db->lastErrorMsg(); } else { echo "Table created successfully\n"; } $db->close(); ?> ---- When the above program is executed, it will create the COMPANY table in your *test.db* and it will display the following messages − [source] ---- Opened database successfully Table created successfully ---- === INSERT Operation Following PHP program shows how to create records in the COMPANY table created in the above example. [source] ---- <?php class MyDB extends SQLite3 { function __construct() { $this->open('test.db'); } } $db = new MyDB(); if(!$db){ echo $db->lastErrorMsg(); } else { echo "Opened database successfully\n"; } $sql =<<<EOF INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ); EOF; $ret = $db->exec($sql); if(!$ret) { echo $db->lastErrorMsg(); } else { echo "Records created successfully\n"; } $db->close(); ?> ---- When the above program is executed, it will create the given records in the COMPANY table and will display the following two lines. [source] ---- Opened database successfully Records created successfully ---- === SELECT Operation Following PHP program shows how to fetch and display records from the COMPANY table created in the above example − [source] ---- <?php class MyDB extends SQLite3 { function __construct() { $this->open('test.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo "Opened database successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = $db->query($sql); while($row = $ret->fetchArray(SQLITE3_ASSOC) ) { echo "ID = ". $row['ID'] . "\n"; echo "NAME = ". $row['NAME'] ."\n"; echo "ADDRESS = ". $row['ADDRESS'] ."\n"; echo "SALARY = ".$row['SALARY'] ."\n\n"; } echo "Operation done successfully\n"; $db->close(); ?> ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 20000 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000 Operation done successfully ---- === UPDATE Operation Following PHP code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table. [source] ---- <?php class MyDB extends SQLite3 { function __construct() { $this->open('test.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo "Opened database successfully\n"; } $sql =<<<EOF UPDATE COMPANY set SALARY = 25000.00 where ID=1; EOF; $ret = $db->exec($sql); if(!$ret) { echo $db->lastErrorMsg(); } else { echo $db->changes(), " Record updated successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = $db->query($sql); while($row = $ret->fetchArray(SQLITE3_ASSOC) ) { echo "ID = ". $row['ID'] . "\n"; echo "NAME = ". $row['NAME'] ."\n"; echo "ADDRESS = ". $row['ADDRESS'] ."\n"; echo "SALARY = ".$row['SALARY'] ."\n\n"; } echo "Operation done successfully\n"; $db->close(); ?> ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully 1 Record updated successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 25000 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000 Operation done successfully ---- === DELETE Operation Following PHP code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table. [source] ---- <?php class MyDB extends SQLite3 { function __construct() { $this->open('test.db'); } } $db = new MyDB(); if(!$db) { echo $db->lastErrorMsg(); } else { echo "Opened database successfully\n"; } $sql =<<<EOF DELETE from COMPANY where ID = 2; EOF; $ret = $db->exec($sql); if(!$ret){ echo $db->lastErrorMsg(); } else { echo $db->changes(), " Record deleted successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = $db->query($sql); while($row = $ret->fetchArray(SQLITE3_ASSOC) ) { echo "ID = ". $row['ID'] . "\n"; echo "NAME = ". $row['NAME'] ."\n"; echo "ADDRESS = ". $row['ADDRESS'] ."\n"; echo "SALARY = ".$row['SALARY'] ."\n\n"; } echo "Operation done successfully\n"; $db->close(); ?> ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully 1 Record deleted successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 25000 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000 Operation done successfully ---- == SQLite - Perl In this chapter, you will learn how to use SQLite in Perl programs. === Installation SQLite3 can be integrated with Perl using Perl DBI module, which is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a standard database interface. Following are simple steps to install DBI module on your Linux/UNIX machine − [source] ---- $ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz $ tar xvfz DBI-1.625.tar.gz $ cd DBI-1.625 $ perl Makefile.PL $ make $ make install ---- If you need to install SQLite driver for DBI, then it can be installed as follows − [source] ---- $ wget http://search.cpan.org/CPAN/authors/id/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz $ tar xvfz DBD-SQLite-1.11.tar.gz $ cd DBD-SQLite-1.11 $ perl Makefile.PL $ make $ make install ---- === DBI Interface APIs Following are important DBI routines, which can suffice your requirement to work with SQLite database from your Perl program. If you are looking for a more sophisticated application, then you can look into Perl DBI official documentation. [%autowidth] |=== |Sr.No.|API & Description |1|*DBI->connect($data_source, "", "", \%attr)* Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds. Datasource has the form like − *DBI:SQLite:dbname = 'test.db'* where SQLite is SQLite driver name and test.db is the name of SQLite database file. If the filename is given as *':memory:'*, it will create an in-memory database in RAM that lasts only for the duration of the session. If the filename is actual device file name, then it attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created. You keep second and third parameter as blank strings and the last parameter is to pass various attributes as shown in the following example. |2|*$dbh->do($sql)* This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here, $dbh is a handle returned by DBI->connect() call. |3|*$dbh->prepare($sql)* This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object. |4|*$sth->execute()* This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here, $sth is a statement handle returned by $dbh->prepare($sql) call. |5|*$sth->fetchrow_array()* This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list. |6|*$DBI::err* This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called. |7|*$DBI::errstr* This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called. |8|*$dbh->disconnect()* This routine closes a database connection previously opened by a call to DBI->connect(). |=== === Connect To Database Following Perl code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. [source] ---- #!/usr/bin/perl use DBI; use strict; my $driver = "SQLite"; my $database = "test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; ---- Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.pl file and execute it as shown below. If the database is successfully created, then it will display the following message − [source] ---- $ chmod +x sqlite.pl $ ./sqlite.pl Open database successfully ---- === Create a Table Following Perl program is used to create a table in the previously created database. [source] ---- #!/usr/bin/perl use DBI; use strict; my $driver = "SQLite"; my $database = "test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; my $stmt = qq(CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);); my $rv = $dbh->do($stmt); if($rv < 0) { print $DBI::errstr; } else { print "Table created successfully\n"; } $dbh->disconnect(); ---- When the above program is executed, it will create COMPANY table in your test.db and it will display the following messages − [source] ---- Opened database successfully Table created successfully ---- *NOTE* − In case you see the following error in any of the operation − [source] ---- DBD::SQLite::st execute failed: not an error(21) at dbdimp.c line 398 ---- In such case, open *dbdimp.c file* available in DBD-SQLite installation and find out *sqlite3_prepare()* function and change its third argument to *-1* instead of 0. Finally, install DBD::SQLite using *make* and do *make install* to resolve the problem. === INSERT Operation Following Perl program shows how to create records in the COMPANY table created in the above example. [source] ---- #!/usr/bin/perl use DBI; use strict; my $driver = "SQLite"; my $database = "test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; my $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 )); my $rv = $dbh->do($stmt) or die $DBI::errstr; $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 )); $rv = $dbh->do($stmt) or die $DBI::errstr; $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )); $rv = $dbh->do($stmt) or die $DBI::errstr; $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );); $rv = $dbh->do($stmt) or die $DBI::errstr; print "Records created successfully\n"; $dbh->disconnect(); ---- When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines − [source] ---- Opened database successfully Records created successfully ---- === SELECT Operation Following Perl program shows how to fetch and display records from the COMPANY table created in the above example. [source] ---- #!/usr/bin/perl use DBI; use strict; my $driver = "SQLite"; my $database = "test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; my $stmt = qq(SELECT id, name, address, salary from COMPANY;); my $sth = $dbh->prepare( $stmt ); my $rv = $sth->execute() or die $DBI::errstr; if($rv < 0) { print $DBI::errstr; } while(my @row = $sth->fetchrow_array()) { print "ID = ". $row[0] . "\n"; print "NAME = ". $row[1] ."\n"; print "ADDRESS = ". $row[2] ."\n"; print "SALARY = ". $row[3] ."\n\n"; } print "Operation done successfully\n"; $dbh->disconnect(); ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 20000 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000 Operation done successfully ---- === UPDATE Operation Following Perl code shows how to UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table. [source] ---- #!/usr/bin/perl use DBI; use strict; my $driver = "SQLite"; my $database = "test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;); my $rv = $dbh->do($stmt) or die $DBI::errstr; if( $rv < 0 ) { print $DBI::errstr; } else { print "Total number of rows updated : $rv\n"; } $stmt = qq(SELECT id, name, address, salary from COMPANY;); my $sth = $dbh->prepare( $stmt ); $rv = $sth->execute() or die $DBI::errstr; if($rv < 0) { print $DBI::errstr; } while(my @row = $sth->fetchrow_array()) { print "ID = ". $row[0] . "\n"; print "NAME = ". $row[1] ."\n"; print "ADDRESS = ". $row[2] ."\n"; print "SALARY = ". $row[3] ."\n\n"; } print "Operation done successfully\n"; $dbh->disconnect(); ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully Total number of rows updated : 1 ID = 1 NAME = Paul ADDRESS = California SALARY = 25000 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000 Operation done successfully ---- === DELETE Operation Following Perl code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table − [source] ---- #!/usr/bin/perl use DBI; use strict; my $driver = "SQLite"; my $database = "test.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; my $stmt = qq(DELETE from COMPANY where ID = 2;); my $rv = $dbh->do($stmt) or die $DBI::errstr; if( $rv < 0 ) { print $DBI::errstr; } else { print "Total number of rows deleted : $rv\n"; } $stmt = qq(SELECT id, name, address, salary from COMPANY;); my $sth = $dbh->prepare( $stmt ); $rv = $sth->execute() or die $DBI::errstr; if($rv < 0) { print $DBI::errstr; } while(my @row = $sth->fetchrow_array()) { print "ID = ". $row[0] . "\n"; print "NAME = ". $row[1] ."\n"; print "ADDRESS = ". $row[2] ."\n"; print "SALARY = ". $row[3] ."\n\n"; } print "Operation done successfully\n"; $dbh->disconnect(); ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully Total number of rows deleted : 1 ID = 1 NAME = Paul ADDRESS = California SALARY = 25000 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000 Operation done successfully ---- == SQLite - Python In this chapter, you will learn how to use SQLite in Python programs. === Installation SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards. To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements. === Python sqlite3 module APIs Following are important sqlite3 module routines, which can suffice your requirement to work with SQLite database from your Python program. If you are looking for a more sophisticated application, then you can look into Python sqlite3 module's official documentation. [%autowidth] |=== |Sr.No.|API & Description |1|*sqlite3.connect(database [,timeout ,other optional arguments])* This API opens a connection to the SQLite database file. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object. When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds). If the given database name does not exist then this call will create the database. You can specify filename with the required path as well if you want to create a database anywhere else except in the current directory. |2|*connection.cursor([cursorClass])* This routine creates a *cursor* which will be used throughout of your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor. |3|*cursor.execute(sql [, optional parameters])* This routine executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style). *For example* − cursor.execute("insert into people values (?, ?)", (who, age)) |4|*connection.execute(sql [, optional parameters])* This routine is a shortcut of the above execute method provided by the cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given. |5|*cursor.executemany(sql, seq_of_parameters)* This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql. |6|*connection.executemany(sql[, parameters])* This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor.s executemany method with the parameters given. |7|*cursor.executescript(sql_script)* This routine executes multiple SQL statements at once provided in the form of script. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by a semi colon (;). |8|*connection.executescript(sql_script)* This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given. |9|*connection.total_changes()* This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened. |10|*connection.commit()* This method commits the current transaction. If you don't call this method, anything you did since the last call to commit() is not visible from other database connections. |11|*connection.rollback()* This method rolls back any changes to the database since the last call to commit(). |12|*connection.close()* This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost! |13|*cursor.fetchone()* This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available. |14|*cursor.fetchmany([size = cursor.arraysize])* This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter. |15|*cursor.fetchall()* This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available. |=== === Connect To Database Following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. [source] ---- #!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; ---- Here, you can also supply database name as the special name *:memory:* to create a database in RAM. Now, let's run the above program to create our database *test.db* in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.py file and execute it as shown below. If the database is successfully created, then it will display the following message. [source] ---- $chmod +x sqlite.py $./sqlite.py Open database successfully ---- === Create a Table Following Python program will be used to create a table in the previously created database. [source] ---- #!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);''') print "Table created successfully"; conn.close() ---- When the above program is executed, it will create the COMPANY table in your *test.db* and it will display the following messages − [source] ---- Opened database successfully Table created successfully ---- === INSERT Operation Following Python program shows how to create records in the COMPANY table created in the above example. [source] ---- #!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (1, 'Paul', 32, 'California', 20000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (2, 'Allen', 25, 'Texas', 15000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )"); conn.commit() print "Records created successfully"; conn.close() ---- When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines − [source] ---- Opened database successfully Records created successfully ---- === SELECT Operation Following Python program shows how to fetch and display records from the COMPANY table created in the above example. [source] ---- #!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], "\n" print "Operation done successfully"; conn.close() ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully ID = 1 NAME = Paul ADDRESS = California SALARY = 20000.0 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- === UPDATE Operation Following Python code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table. [source] ---- #!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1") conn.commit() print "Total number of rows updated :", conn.total_changes cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], "\n" print "Operation done successfully"; conn.close() ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully Total number of rows updated : 1 ID = 1 NAME = Paul ADDRESS = California SALARY = 25000.0 ID = 2 NAME = Allen ADDRESS = Texas SALARY = 15000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- === DELETE Operation Following Python code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table. [source] ---- #!/usr/bin/python import sqlite3 conn = sqlite3.connect('test.db') print "Opened database successfully"; conn.execute("DELETE from COMPANY where ID = 2;") conn.commit() print "Total number of rows deleted :", conn.total_changes cursor = conn.execute("SELECT id, name, address, salary from COMPANY") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "ADDRESS = ", row[2] print "SALARY = ", row[3], "\n" print "Operation done successfully"; conn.close() ---- When the above program is executed, it will produce the following result. [source] ---- Opened database successfully Total number of rows deleted : 1 ID = 1 NAME = Paul ADDRESS = California SALARY = 20000.0 ID = 3 NAME = Teddy ADDRESS = Norway SALARY = 20000.0 ID = 4 NAME = Mark ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully ---- ----