15条SQLite3语句

 

转自:http://www.thegeekstuff.com/2012/09/sqlite-command-examples/

SQLite3 is very lightweight SQL database which focuses on simplicity more than anything else. This is a self-contained serverless database engine, which is very simple to install and use.

While most of the commands in the SQLite are similar to SQL commands of other datbases like MySQL and ORACLE, there are some SQLite SQL commands that are different.

This article explains all the basic SQL commands that you need to know to use the SQLite database effectively.

If you don’t have sqlite installed, execute “yum install sqlite” to install it. You can also install SQLite database from source to get the latest version.

1. Create a SQLite Database (and a Table)

First, let us understand how create a SQLite database with couple of tables, populate some data, and view those records.

The following example creates a database called employee.db. This also creates an employee table with 3 columns (id, name and title), and a department table in the company.db database. We’ve purposefully missed the deptid column in the employee table. We’ll see how to add that later.

# sqlite3 company.db
sqlite> create table employee(empid integer,name varchar(20),title varchar(10));
sqlite> create table department(deptid integer,name varchar(20),location varchar(10));
sqlite> .quit

Note: To exit from the SQLite commandline “sqlite>” prompt, type “.quit” as shown above.

A SQLite database is nothing but a file that gets created under your current directory as shown below.

 
# ls -l company.db -rw-r--r--. 1 root root 3072 Sep 19 11:21 company.db

2. Insert Records

The following example populates both employee and department table with some sample records.

You can execute all the insert statements from the sqlite command line, or you can add those commands into a file and execute the file as shown below.

First, create a insert-data.sql file as shown below.

# vi insert-data.sql
insert into employee values(101,'John Smith','CEO');
insert into employee values(102,'Raj Reddy','Sysadmin');
insert into employee values(103,'Jason Bourne','Developer');
insert into employee values(104,'Jane Smith','Sale Manager');
insert into employee values(105,'Rita Patel','DBA');
insert into department values(1,'Sales','Los Angeles');
insert into department values(2,'Technology','San Jose');
insert into department values(3,'Marketing','Los Angeles');

The following will execute all the commands from the insert-data.sql in the company.db database

# sqlite3 company.db < insert-data.sql

3. View Records

Once you’ve inserted the records, view it using select command as shown below.

# sqlite3 company.db
sqlite> select * from employee;
101|John Smith|CEO
102|Raj Reddy|Sysadmin
103|Jason Bourne|Developer
104|Jane Smith|Sale Manager
105|Rita Patel|DBA
sqlite> select * from department;
1|Sales|Los Angeles
2|Technology|San Jose
3|Marketing|Los Angeles

4. Rename a Table

The following example renames department table to dept using the alter table command.

sqlite> alter table department rename to dept;

5. Add a Column to an Existing Table

The following examples adds deptid column to the existing employee table;

sqlite> alter table employee add column deptid integer;

Update the department id for the employees using update command as shown below.

update employee set deptid=3 where empid=101;
update employee set deptid=2 where empid=102;
update employee set deptid=2 where empid=103;
update employee set deptid=1 where empid=104;
update employee set deptid=2 where empid=105;

Verify that the deptid is updated properly in the employee table.

sqlite> select * from employee;
101|John Smith|CEO|3
102|Raj Reddy|Sysadmin|2
103|Jason Bourne|Developer|2
104|Jane Smith|Sale Manager|1
105|Rita Patel|DBA|2

6. View all Tables in a Database

Execute the following command to view all the tables in the current database. The folowing example shows that there are two tables in the current database.

sqlite> .tables dept      employee

7. Create an Index

The following example creates an unique index called empidx on the empid field of employee table.

sqlite> create unique index empidx on employee(empid);

Once an unique index is created, if you try to add another record with an empid that already exists, you’ll get an error as shown below.

sqlite> insert into employee values (101,'James Bond','Secret Agent',1);
Error: constraint failed

8. Create a Trigger

For this example, first add a date column called “updatedon” on employee table.

sqlite> alter table employee add column updatedon date;

Next, create a file that has the trigger definition. The following trigger will update the “updatedon” date column with the current timestamp whenever you perform an update on this table.

# vi employee_update_trg.sql
create trigger employee_update_trg after update on employee
begin
update employee set updatedon = datetime('NOW') where rowid = new.rowid;
end;

Create the trigger on the company.db database as shown below.

# sqlite3 company.db < employee_update_trg.sql

Now anytime you update any record in the employee table, the “updatedon” date column will be updated with the current timestamp as shown below. The following example updates the “updatedon” timestamp for empid 104 through trigger.

# sqlite3 company.db
sqlite> update employee set title='Sales Manager' where empid=104;
sqlite> select * from employee;
101|John Smith|CEO|3|
102|Raj Reddy|Sysadmin|2|
103|Jason Bourne|Developer|2|
104|Jane Smith|Sales Manager|1|2012-09-15 18:29:28 105|Rita Patel|DBA|2|

9. Create a View

The following example creates a view called “empdept”, which combines fields from both employee and dept table.

sqlite> create view empdept as select empid, e.name, title, d.name, location from employee e, dept d where e.deptid = d.deptid;

Now you can execute select command on this view just like a regular table.

sqlite> select * from empdept;
101|John Smith|CEO|Marketing|Los Angeles
102|Raj Reddy|Sysadmin|Technology|San Jose
103|Jason Bourne|Developer|Technology|San Jose
104|Jane Smith|Sales Manager|Sales|Los Angeles
105|Rita Patel|DBA|Technology|San Jose

After creating a view, if you execute .tables, you’ll also see the view name along with the tables.

sqlite> .tables
deptempdept employee

10. SQLite Savepoint, Rollback, Commit

Currently dept table has the following 3 records.

sqlite> select * from dept;
1|Sales|Los Angeles
2|Technology|San Jose
3|Marketing|Los Angeles

Now, create a savepoint called “major”, and perform some transactions on the dept table. As you see below, we’ve added two records, deleted one record, after creating a savepoint called “major”.

sqlite> savepoint major;
sqlite> insert into dept values(4,'HR','Los Angeles');
sqlite> insert into dept values(5,'Finance','San Jose');
sqlite> delete from dept where deptid=1;
sqlite> select * from dept;
2|Technology|San Jose
3|Marketing|Los Angeles
4|HR|Los Angeles
5|Finance|San Jose

Now for some reason, if we don’t want the above transactions, we can rollback the changes to a particular savepoint. In this example, we are rolling back all the changes we’ve made after the “major” savepoint.

sqlite> rollback to savepoint major;
sqlite> select * from dept;
1|Sales|Los Angeles
2|Technology|San Jose
3|Marketing|Los Angeles

If you don’t want your savepoints anymore, you can erase it using release command.

sqlite> release savepoint major;

11. Additional Date Functions

By default, the date columns values displayed in UTC time. To display in the local time, use the datetime command on the date column as shown below.

sqlite> select empid,datetime(updatedon,'localtime') from employee;
104|2012-09-15 11:29:28

You can also use strftime to display the date column in various output.

sqlite> select empid,strftime('%d-%m-%Y %w %W',updatedon) from employee;
104|19-09-2012 3 38

The following are the possible modifers you can use in the strftime function.

  • %d day of month: 00
  • %f fractional seconds: SS.SSS
  • %H hour: 00-24
  • %j day of year: 001-366
  • %J Julian day number
  • %m month: 01-12
  • %M minute: 00-59
  • %s seconds since 1970-01-01
  • %S seconds: 00-59
  • %w day of week 0-6 with Sunday==0
  • %W week of year: 00-53
  • %Y year: 0000-9999
  • %% %

12. Dropping Objects

You can drop all the above created objects using the appropriate drop command as shown below.

Since we are dropping objects for testing purpose, copy the company.db to a test.db and try these commands on the test.db

# cp company.db test.db  #
sqlite3 test.db
sqlite> .tables deptempdept employee
sqlite> drop index empidx;
sqlite> drop trigger employee_update_trg;
sqlite> drop view empdept; sqlite>
drop table employee;
sqlite> drop table dept;

All the tables and views from the test.db are now deleted.

sqlite> .tables
sqlite>

Note: When you drop a table all the indexes and triggers for that table are also dropped.

13. Operators

The following are the possible operators you can use in SQL statements.

  • ||
  • * / %
  • + -
  • << >> & |
  • < >=
  • = == != <> IS IS NOT IN LIKE GLOB MATCH REGEXP
  • AND OR

For example:

sqlite> select * from employee where empid >= 102 and empid  select * from dept where location like 'Los%';
1|Sales|Los Angeles
3|Marketing|Los Angeles

14. Explain Query Plan

Execute “explain query plan”, to get information about the table that is getting used in a query or view. This is very helpful when you are debugging a complex query with multiple joins on several tables.

sqlite> explain query plan select * from empdept; 0|0|TABLE employee AS e 1|1|TABLE dept AS d

For a detailed trace, just execute “explain” followed by the query to get more performance data on the query. This is helpful for debugging purpose when the query is slow.

sqlite> explain select empid,strftime('%d-%m-%Y %w %W',updatedon) from employee;
0|Trace|0|0|0||00|
1|Goto|0|12|0||00|
2|OpenRead|0|2|0|4|00|
3|Rewind|0|10|0||00|
4|Column|0|0|1||00|
5|String8|0|3|0|%d-%m-%Y %w %W|00|
6|Column|0|3|4||00|
7|Function|1|3|2|strftime(-1)|02|
8|ResultRow|1|2|0||00|
9|Next|0|4|0||01|
10|Close|0|0|0||00|
11|Halt|0|0|0||00|
12|Transaction|0|0|0||00|
13|VerifyCookie|0|19|0||00|
14|TableLock|0|2|0|employee|00|
15|Goto|0|2|0||00|

15. Attach and Detach Database

When you have multiple database, you can use attach command to execute queries across database.

For example, if you have two database that has the same table name with different data, you can create a union query across the database to view the combined records as explained below.

In this example, we have two company database (company1.db and company2.db). From the sqlite prompt, attach both these database by giving alias as c1 and c2 as shown below.

# sqlite3 sqlite> attach database 'company1.db' as c1;
sqlite> attach database 'company2.db' as c2;

Execute “.database” command which will display all the attached databases.

sqlite> .database
seq name file
--- --------------- ------------------
0 main
2 c1 /root/company1.db
3 c2 /root/company2.db

Now, you can execute a union query across these databases to combine the results.

sqlite> select empid, name, title from c1.employee union select empid, name, title from c2.employee;
101|John Smith|CEO
102|Raj Reddy|Sysadmin
103|Jason Bourne|Developer
104|Jane Smith|Sales Manager
105|Rita Patel|DBA
201|James Bond|Secret Agent
202|Spider Man|Action Hero

After attaching a database, from the current sqlite session, if you want to detach it, use detach command as shown below.

sqlite> detach c1; 
 sqlite> .database
 seq name file 
--- --------------- ----------------- 
0 main 
2 c2 /root/company2.db

15条SQLite3语句的更多相关文章

  1. 『片段』OracleHelper (支持 多条SQL语句)

    C# 调用 Oracle 是如此尴尬 >System.Data.OracleClient.dll —— .Net 自带的 已经 过时作废. >要链接 Oracle 服务器,必须在 本机安装 ...

  2. sql执行万条update语句优化

    几个月没有更新笔记了,最近遇到一个坑爹的问题,顺道记录一下.. 需求是这样的:一次性修改上万条数据库. 项目是用MVC+linq的. 本来想着用 直接where() 1 var latentCusto ...

  3. SQL反模式学习笔记18 减少SQL查询数据,避免使用一条SQL语句解决复杂问题

    目标:减少SQL查询数据,避免使用一条SQL语句解决复杂问题 反模式:视图使用一步操作,单个SQL语句解决复杂问题 使用一个查询来获得所有结果的最常见后果就是产生了一个笛卡尔积.导致查询性能降低. 如 ...

  4. 假设result是一个float型变量,其值为27.32,value是一个int型变量,其值为15执行以下语句后,两个便利的值分别是多少?为什么?

    假设result是一个float型变量,其值为27.32,value是一个int型变量,其值为15执行以下语句后,两个便利的值分别是多少?为什么? 在执行这条语句的过程中,保存在result中的值被读 ...

  5. 一条sql语句引发的遐想:select t.*, t.rowid from STUDENT t

    在学习oracle 过程当中,当在看tables时,比如STUDENT,右击——查看——查询,会自动有这样的一条查询语句: select t.*, t.rowid from STUDENT_TJB t ...

  6. 关联映射、关联查询【重点掌握一条SQL语句的那种方法】

    1 什么叫关联映射 通过数据库对象之间的关联关系(一对一.一对多.多对多),反映到实体对象上之间的引用. 举例 用户实体类(User):user_id user_name user_token 笔记本 ...

  7. 用一条mysql语句插入多条数据

    这篇文章主要介绍了在mysql中使用一条sql语句插入多条数据,效率非常高,但是原理其实很简单,希望对大家有所帮助 假如有一个数据表A: id name title addtime 如果需要插入n条数 ...

  8. TPCH 22条SQL语句分析

    使用TPC-H进行性能测试,需要有很多工作配合才能获得较高性能,如建立索引,表数据的合理分布(使用表空间和聚簇技术)等.本文从查询优化技术的角度,对TPC-H的22条查询语句和主流数据库执行每条语句对 ...

  9. MySQL中一条更新语句是如何执行的

    1.创建表的语句和更新的语句 这个表的创建语句,这个表有一个主键ID和一个整型字段c: mysql> create table T(ID int primary key, c int); 如果要 ...

随机推荐

  1. VC 实现程序只运行一个实例,并激活已运行的程序

    转载:http://blog.sina.com.cn/s/blog_4b44e1c00100bh69.html 进程的互斥运行:CreateMutex函数实现只运行一个程序实例 正常情况下,一个进程的 ...

  2. python设计模式-命令模式

    命令模式就是对命令的封装.所谓封装命令,就是将一系列操作封装到命令类中,并且命令类只需要对外公开一个执行方法execute,调用此命令的对象只需要执行命令的execute方法就可以完成所有的操作.这样 ...

  3. eclips注释的快捷键

    一 . 注释java或者c++ 代码的快捷键 CTRL + / 二.  注释xml格式的快捷键 注释: CTRL + SHIFT + / 取消注释: CTRL + SHIFT + \

  4. [Hadoop] Yarn & k8s

    写在前面 一.大数据全栈 头两节讲完HDFS & MapReduce,这一部分聊一聊它们之间的“人物关系”. 其中也讨论下k8s的学习必要性. Ref: [Distributed ML] Yi ...

  5. Go项目实战:打造高并发日志采集系统(二)

    日志统计系统的整体思路就是监控各个文件夹下的日志,实时获取日志写入内容并写入kafka队列,写入kafka队列可以在高并发时排队,而且达到了逻辑解耦合的目的.然后从kafka队列中读出数据,根据实际需 ...

  6. 在VM虚拟机Windows Server r2上部署安装Microsoft Dynamics CRM 2016 步骤详解(一)

    应公司需求,最近在学微软的Dynamics CRM.在搭建环境的过程中也遇到了一些雷坑,在这里分享一下安装部署过程当中所遇到的一些问题, 安装Microsoft Dynamics CRM 2016的几 ...

  7. PJzhang:CVE-2019-14287 sudo权限绕过漏洞复现

    猫宁!!! 参考链接:Ms08067实验室公众号 sudo 1.8.28版本之前有漏洞. 更新完kali linux,deepin截图工具失效,只能用自带的,不能划重点. 看一下sudo版本,1.8. ...

  8. 【AMAD】django-oauth-toolkit -- 为Django集成Oauth2加入一些好货!

    简介 个人评分 简介 如果你面对下面其中的一个问题: 你的Django app需要暴露一个接口,你希望能够收到Oauth2协议的保护 你需要实现Oauth2鉴权服务器,让你的基础设施可以进行token ...

  9. 【C/C++开发】【VS开发】win32位与x64位下各类型长度对比

    64 位的优点:64 位的应用程序可以直接访问 4EB 的内存和文件大小最大达到4 EB(2 的 63 次幂):可以访问大型数据库.本文介绍的是64位下C语言开发程序注意事项. 1. 32 位和 64 ...

  10. 现代化的拷贝文字---clipboard.js

    参考链接:http://www.clipboardjs.cn/