本文所用数据来源:https://github.com/fivethirtyeight/data/tree/master/college-names
#数据展示
SELECT [columnA, columnB, ...]
FROM tableName;
#如: 查询数据库中code和name两列的数据
SELECT code, name
FROM facts;
#条件查询,使用where来界定查询条件,如,查询人口大于1亿的国家代码和名称
SELECT code, name
FROM facts
WHERE population> 100000000;
在where语句中可以使用的比较符号:
小于或等于: <=
大于或等于: >=
等于: =
不等于: !=
sqlite中可以直接对日期数据进行比较,譬如,查询在2015-11-01 14:00之前创建的数据
SELECT * FROM facts
WHERE created_at < "2015-11-01 14:00"
注意:在双引号中就是日期格式的数据,必须按照yyyy-mm-dd HH:MM:SS的格式
限定返回的数据数量
# 有时候只想查看返回数据的前几条,使用limit, 如:查询前五条数据
select * from facts limit 5;
SELECT [column1, column2,...] FROM [table1]
WHERE [condition1] AND [condition2]
#如,人口大于1亿且国土面积大于100000的国家名称
select name from facts where population> 100000000 and area_land> 100000 limit 10;
select
name
from
facts
order
by
name
desc
limit
10
;
#多列排序,譬如,在一个存储人名的表中,首先对姓排序,然后在同一个姓中再对名排序
select
[
column1, column2..
]
from
table_name
order
by
column1 (
asc
or
desc
), column2 (
asc
or
desc
)
#结果会返回一个列表(截取):
[
[0, "id", "INTEGER", 1, null, 1
]
,
[
1, "code", "varchar(255)", 1, null, 0
]
,
[
2, "name", "varchar(255)", 1, null, 0
]
]
该列表的内容内容如下,pk = 1表明该字段是一个主键:
INSERT
INTO
facts
VALUES
(
262
, "dq", "DataquestLand",
60000
,
40000
,
20000
,
500000
,
100
,
50
,
10
,
20
, "
2016
-
02
-
25
12
:
00
:
00
", "
2016
-
02
-
25
12
:
00
:
00
");
如果要插入的数据中有空值,就用NULL代替即可
UPDATE tableName
SET column1=value1, column2=value2, ...
WHERE column1=value3, column2=value4, ...
# 例如,将United States改为DataquestLand
update facts
set name='DataquestLand'
where name='United States';
conn
=
sqlite3.connect("countries.db") # 连接数据库
cursor
=
conn.
cursor
() # 返回一个cursor对象
query
=
'
select name from facts;
'
# 将查询语句保存为字符串格式
cursor
.
execute
(query) # 执行查询语句
names
=
cursor
.fetchall() # 保存全部的返回结果
print
(names
[
0:2
]
) # 显示前两个数据
#结果:一个列表,列表中的每个元素是一个元组
[
('Afghanistan,), ('Albania',)
]
有时候可能需要逐条返回查询结果,就是用fetchone(),需要一次返回n条结果,就是用fetchmany(n)。因为在cursor对象中会保存一个内部的计数器,在每次得到返回结果时都会增加计数器
# 上面的查询语句等价于这样
import sqlite3
conn = sqlite3.connect("countries.db") # 连接数据库
cursor = conn.cursor() # 返回一个cursor对象
query = 'select name from facts;' # 将查询语句保存为字符串格式
cursor.execute(query) # 执行查询语句
names = cursor.fetchmany(2) # 保存前2条结果
print(names)
在某个进程连接着一个sqlite数据库的时候,其他进程是不能访问该数据库的,所以在操作完数据库之后需要关闭连接,注意,在关闭连接的时候,之前对数据库的更改会自动保存并生效。
conn = sqlite3.connect("countries.db")
conn.close()
INNER JOIN - 只展示符合查询条件的值,在上图中就是左边的country值等于右边id_1的值的那些行
LEFT OUTER JOIN - 左表中有不匹配的数据时,在合并的表中的其他字段就显示为NULL
关于JOIN,更多资料参考:http://www.yiibai.com/sqlite/sqlite_using_joins.html