X Tutup
Skip to content

Commit abb6208

Browse files
committed
sqlite
1 parent a51275b commit abb6208

File tree

4 files changed

+146
-0
lines changed

4 files changed

+146
-0
lines changed

233.md

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
>然而,敬虔加上知足的心便是大利了,因为我们没有带什么到世上来,也不能带什么去,只要有衣有食,就当知足。但那些想要发财的人,就陷在迷惑、落在网罗和许多无知有害的私欲里,叫人沉在败坏和灭亡中。贪财是万恶之根。有人贪恋钱财,就被引诱离了真道,用许多愁苦把自己刺透了。(1 TIMOTHY 6:6-10)
2+
3+
#SQLite数据库
4+
5+
SQLite是一个小型的关系型数据库,它最大的特点在于不需要服务器、零配置。在前面的两个服务器,不管是MySQL还是MongoDB,都需要“安装”,安装之后,它运行起来,其实是已经有一个相应的服务器在跑着呢。而SQLite不需要这样,首先python已经将相应的驱动模块作为标准库一部分了,只要安装了python,就可以使用;另外,它也不需要服务器,可以类似操作文件那样来操作SQLite数据库文件。还有一点也不错,SQLite源代码不受版权限制。
6+
7+
SQLite也是一个关系型数据库,所以SQL语句,都可以在里面使用。
8+
9+
跟操作mysql数据库类似,对于SQLite数据库,也要通过以下几步:
10+
11+
- 建立连接对象
12+
- 连接对象方法:建立游标对象
13+
- 游标对象方法:执行sql语句
14+
15+
##建立连接对象
16+
17+
由于SQLite数据库的驱动已经在python里面了,所以,只要引用就可以直接使用
18+
19+
>>> import sqlite3
20+
>>> conn = sqlite3.connect("23301.db")
21+
22+
这样就得到了连接对象,是不是比mysql连接要简化了很多呢。在`sqlite3.connect("23301.db")`语句中,如果已经有了那个数据库,就连接上它;如果没有,就新建一个。注意,这里的路径可以随意指定的。
23+
24+
不妨到目录中看一看,是否存在了刚才建立的数据库文件。
25+
26+
/2code$ ls 23301.db
27+
23301.db
28+
29+
果然有了一个文件。
30+
31+
连接对象建立起来之后,就要使用连接对象的方法继续工作了。
32+
33+
>>> dir(conn)
34+
['DataError', 'DatabaseError', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning', '__call__', '__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'commit', 'create_aggregate', 'create_collation', 'create_function', 'cursor', 'enable_load_extension', 'execute', 'executemany', 'executescript', 'interrupt', 'isolation_level', 'iterdump', 'load_extension', 'rollback', 'row_factory', 'set_authorizer', 'set_progress_handler', 'text_factory', 'total_changes']
35+
36+
##游标对象
37+
38+
这步跟mysql也类似,要建立游标对象。
39+
40+
>>> cur = conn.cursor()
41+
42+
接下来对数据库内容的操作,都是用游标对象方法来实现了:
43+
44+
>>> dir(cur)
45+
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'arraysize', 'close', 'connection', 'description', 'execute', 'executemany', 'executescript', 'fetchall', 'fetchmany', 'fetchone', 'lastrowid', 'next', 'row_factory', 'rowcount', 'setinputsizes', 'setoutputsize']
46+
47+
是不是看到熟悉的名称了:`close(), execute(), executemany(), fetchall()`
48+
49+
###创建数据库表
50+
51+
在mysql中,我们演示的是利用mysql的shell来创建的表。其实,当然可以使用sql语句,在python中实现这个功能。这里对sqlite数据库,就如此操作一番。
52+
53+
>>> create_table = "create table books (title text, author text, lang text) "
54+
>>> cur.execute(create_table)
55+
<sqlite3.Cursor object at 0xb73ed5a0>
56+
57+
这样就在数据库23301.db中建立了一个表books。对这个表可以增加数据了:
58+
59+
>>> cur.execute('insert into books values ("from beginner to master", "laoqi", "python")')
60+
<sqlite3.Cursor object at 0xb73ed5a0>
61+
62+
为了保证数据能够保存,还要(这是多么熟悉的操作流程和命令呀):
63+
64+
>>> conn.commit()
65+
>>> cur.close()
66+
>>> conn.close()
67+
68+
支持,刚才建立的那个数据库中,已经有了一个表books,表中已经有了一条记录。
69+
70+
整个流程都不陌生。
71+
72+
###查询
73+
74+
存进去了,总要看看,这算强迫症吗?
75+
76+
>>> conn = sqlite3.connect("23301.db")
77+
>>> cur = conn.cursor()
78+
>>> cur.execute('select * from books')
79+
<sqlite3.Cursor object at 0xb73edea0>
80+
>>> print cur.fetchall()
81+
[(u'from beginner to master', u'laoqi', u'python')]
82+
83+
###批量插入
84+
85+
多增加点内容,以便于做别的操作:
86+
87+
>>> books = [("first book","first","c"), ("second book","second","c"), ("third book","second","python")]
88+
89+
这回来一个批量插入
90+
91+
>>> cur.executemany('insert into books values (?,?,?)', books)
92+
<sqlite3.Cursor object at 0xb73edea0>
93+
>>> conn.commit()
94+
95+
用循环语句打印一下查询结果:
96+
97+
>>> rows = cur.execute('select * from books')
98+
>>> for row in rows:
99+
... print row
100+
...
101+
(u'from beginner to master', u'laoqi', u'python')
102+
(u'first book', u'first', u'c')
103+
(u'second book', u'second', u'c')
104+
(u'third book', u'second', u'python')
105+
106+
###更新
107+
108+
正如前面所说,在cur.execute()中,你可以写SQL语句,来操作数据库。
109+
110+
>>> cur.execute("update books set title='physics' where author='first'")
111+
<sqlite3.Cursor object at 0xb73edea0>
112+
>>> conn.commit()
113+
114+
按照条件查处来看一看:
115+
116+
>>> cur.execute("select * from books where author='first'")
117+
<sqlite3.Cursor object at 0xb73edea0>
118+
>>> cur.fetchone()
119+
(u'physics', u'first', u'c')
120+
121+
###删除
122+
123+
在sql语句中,这也是常用的。
124+
125+
>>> cur.execute("delete from books where author='second'")
126+
<sqlite3.Cursor object at 0xb73edea0>
127+
>>> conn.commit()
128+
129+
>>> cur.execute("select * from books")
130+
<sqlite3.Cursor object at 0xb73edea0>
131+
>>> cur.fetchall()
132+
[(u'from beginner to master', u'laoqi', u'python'), (u'physics', u'first', u'c')]
133+
134+
不要忘记,在你完成对数据库的操作是,一定要关门才能走人:
135+
136+
>>> cur.close()
137+
>>> conn.close()
138+
139+
作为基本知识,已经介绍差不多了。当然,在实践的编程中,或许会遇到问题,就请读者多参考官方文档:[https://docs.python.org/2/library/sqlite3.html](https://docs.python.org/2/library/sqlite3.html)
140+
141+
------
142+
143+
[总目录](./index.md)&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;[上节:MongoDB数据库](./232.md)&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;[下节:电子表格](./234.md)
144+
145+
如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。

2code/23301.db

2 KB
Binary file not shown.

2code/23301.sqlite

2 KB
Binary file not shown.

index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
2. [MySQL数据库(1)](./230.md)==>MySQL概况,安装,python连接MySQL模块和方法
9797
3. [MySQL数据库(2)](./231.md)==>连接对象方法,游标对象方法:数据库的增删改查基本操作
9898
4. [MongoDB数据库](./232.md)==>mongodb的安装启动,pymongo模块:连接客户端,数据库的增删改查操作
99+
5. [SQLite数据库](./233.md)==>通过sqlite3模块操作SQLite数据库:连接对象方法,游标对象方法,数据库增删改查
99100

100101

101102
#第叁季 实战

0 commit comments

Comments
 (0)
X Tutup