44.md 7.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11
# Python 数据库编程:SQLite(教程)

> 原文: [https://pythonspot.com/python-database-programming-sqlite-tutorial/](https://pythonspot.com/python-database-programming-sqlite-tutorial/)

在本教程中,您将学习如何在 Python 中使用 SQLite [数据库](https://pythonspot.com/python-database/)管理系统。 您将学习如何使用 SQLite,SQL 查询,RDBMS 以及更多有趣的东西!


## Pyton 数据库

![Python Database ](img/4c7e8cbef62872a3c49fc4085527514d.jpg)

W
wizardforcel 已提交
12
Python 数据库。
W
init  
wizardforcel 已提交
13

W
wizardforcel 已提交
14
使用 SQL 语言从数据库系统检索数据。 数据无处不在,软件应用程序使用它。 数据位于内存,文件或数据库中。
W
init  
wizardforcel 已提交
15

W
wizardforcel 已提交
16
Python 具有许多数据库系统的绑定,包括 [MySQL](https://pythonspot.com/mysql-with-python), [Postregsql](https://pythonspot.com/python-database-postgresql/), Oracle, Microsoft SQL Server 和 Maria DB。
W
init  
wizardforcel 已提交
17

W
wizardforcel 已提交
18 19 20
这些数据库管理系统(DBMS)之一称为 SQLite。 SQLite 创建于 2000 年,是数据库动物园中众多管理系统之一。

SQL 是专用于管理[数据库](https://pythonspot.com/python-database/)中保存的数据的专用编程语言。该语言自 1986 年以来一直存在,值得学习。[这是关于 SQL 的古老有趣的视频](https://www.youtube.com/watch?v=5ycx9hFGHog)
W
init  
wizardforcel 已提交
21

W
wizardforcel 已提交
22
## SQLite
W
init  
wizardforcel 已提交
23 24 25

![SQLite](img/b49bf74e6651a4fea2a00aefd48f3b71.jpg)

W
wizardforcel 已提交
26
SQLite,一个关系数据库管理系统。SQLite 是世界上部署最广泛的 SQL 数据库引擎。SQLite 的源代码位于公共领域。
W
init  
wizardforcel 已提交
27

W
wizardforcel 已提交
28
它是一个自包含,无服务器,零配置的事务型 SQL 数据库引擎。SQLite 项目由彭博社和 Mozilla 赞助。
W
init  
wizardforcel 已提交
29 30 31

## 安装 SQLite:

W
wizardforcel 已提交
32
使用此命令安装 SQLite:
W
init  
wizardforcel 已提交
33 34 35 36 37 38

```py
$ sudo apt-get install sqlite

```

W
wizardforcel 已提交
39
验证是否正确安装。 复制此程序并将其另存为`test1.py`
W
init  
wizardforcel 已提交
40 41 42 43 44 45 46 47 48 49 50

```py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = None

try:
W
wizardforcel 已提交
51 52 53 54 55 56 57 58 59 60 61
    con = lite.connect('test.db')
    cur = con.cursor()  
    cur.execute('SELECT SQLITE_VERSION()')
    data = cur.fetchone()
    print "SQLite version: %s" % data                
except lite.Error, e:   
    print "Error %s:" % e.args[0]
    sys.exit(1)
finally:    
    if con:
        con.close()
W
init  
wizardforcel 已提交
62 63 64

```

W
wizardforcel 已提交
65
执行:
W
init  
wizardforcel 已提交
66 67 68 69 70 71

```py
$ python test1.py

```

W
wizardforcel 已提交
72
它应该输出:
W
init  
wizardforcel 已提交
73 74 75 76 77 78

```py
SQLite version: 3.8.2

```

W
wizardforcel 已提交
79
## 上面的脚本做了什么?
W
init  
wizardforcel 已提交
80

W
wizardforcel 已提交
81
该脚本使用以下代码行连接到名为`test.db`的新数据库:
W
init  
wizardforcel 已提交
82 83 84 85 86 87

```py
con = lite.connect('test.db')

```

W
wizardforcel 已提交
88
然后,它使用以下命令查询数据库管理系统
W
init  
wizardforcel 已提交
89 90 91 92 93 94

```py
SELECT SQLITE_VERSION()

```

W
wizardforcel 已提交
95
依次返回其版本号。 该行称为 SQL 查询。
W
init  
wizardforcel 已提交
96 97 98

## SQL 创建和插入

W
wizardforcel 已提交
99
下面的脚本会将数据存储到名为`user.db`的新数据库中
W
init  
wizardforcel 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

```py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('user.db')

with con:

    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
    cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")

```

W
wizardforcel 已提交
120
SQLite 是使用表的数据库管理系统。 这些表可以与其他表建立关系:称为关系数据库管理系统或 RDBMS。 该表定义了数据的结构并可以保存数据。 数据库可以容纳许多不同的表。 使用以下命令创建表:
W
init  
wizardforcel 已提交
121 122 123 124 125 126

```py
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")

```

W
wizardforcel 已提交
127
我们使用以下命令将记录添加到表中:
W
init  
wizardforcel 已提交
128 129 130 131 132 133 134

```py
cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")

```

W
wizardforcel 已提交
135
第一个值是 ID。 第二个值是名称。 一旦运行脚本,数据便被插入到数据库表`Users`中:
W
init  
wizardforcel 已提交
136 137 138

![SQL Table](img/6331a77064535de9dc0a93e8b103f00d.jpg)

W
wizardforcel 已提交
139
SQL 表
W
init  
wizardforcel 已提交
140 141 142

## SQLite 查询数据

W
wizardforcel 已提交
143
我们可以使用两种方法浏览数据库:命令行和图形界面。
W
init  
wizardforcel 已提交
144

W
wizardforcel 已提交
145
从控制台:要使用命令行进行浏览,请键入以下命令:
W
init  
wizardforcel 已提交
146 147 148 149 150 151 152 153

```py
sqlite3 user.db
.tables
SELECT * FROM Users;

```

W
wizardforcel 已提交
154
这将在表`Users`中输出数据。
W
init  
wizardforcel 已提交
155 156 157 158 159 160 161 162 163

```py
sqlite> SELECT * FROM Users;
1|Michelle
2|Sonya
3|Greg

```

W
wizardforcel 已提交
164
从 GUI:如果要使用 GUI,则有很多选择。 我个人选择了 sqllite-man,但还有[很多其他](https://stackoverflow.com/questions/835069/which-sqlite-administration-console-do-you-recommend)。我们使用以下方法安装:
W
init  
wizardforcel 已提交
165 166 167 168 169 170 171 172 173 174 175 176

```py
sudo apt-get install sqliteman

```

我们启动应用程序 sqliteman。 gui 弹出。

![sqliteman](img/e57ee6ed25a87b23c3a3cfe92e1fa1fe.jpg)

sqliteman

W
wizardforcel 已提交
177
按“文件 > 打开 > `user.db`”。 似乎变化不大,不用担心,这只是用户界面。 左侧是一棵小树状视图,请按“表 > 用户”。 现在将显示包括所有记录的完整表格。
W
init  
wizardforcel 已提交
178 179 180 181 182 183 184 185 186

![sqliteman](img/60354a5e7e39d04c97a1ee14b3b5db1b.jpg)

sqliteman

该 GUI 可用于修改表中的记录(数据)并添加新表。

## SQL 数据库查询语言

W
wizardforcel 已提交
187
SQL 有许多命令可以与[数据库](https://pythonspot.com/python-database/)进行交互。 您可以从命令行或 GUI 尝试以下命令:
W
init  
wizardforcel 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

```py
sqlite3 user.db 
SELECT * FROM Users;
SELECT count(*) FROM Users;
SELECT name FROM Users;
SELECT * FROM Users WHERE id = 2;
DELETE FROM Users WHERE id = 6;

```

我们可以在 Python 程序中使用这些查询:

```py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('user.db')

with con:    

    cur = con.cursor()    
    cur.execute("SELECT * FROM Users")

    rows = cur.fetchall()

    for row in rows:
        print row

```

W
wizardforcel 已提交
222
这将从数据库输出`Users`表中的所有数据:
W
init  
wizardforcel 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236

```py
$ python get.py 
(1, u'Michelle')
(2, u'Sonya')
(3, u'Greg')

```

## 创建用户信息数据库


我们可以跨多个表构建数据。 这使我们的数据保持结构化,快速和有条理。 如果我们只有一个表来存储所有内容,那么很快就会陷入混乱。 我们将要做的是创建多个表并将它们组合使用。 我们创建两个表:

W
wizardforcel 已提交
237
`Users`
W
init  
wizardforcel 已提交
238 239 240 241 242

![SQL Table](img/f713e77b9a67592c539974f0fd3c7bbe.jpg)

SQL Table

W
wizardforcel 已提交
243
`Jobs`
W
init  
wizardforcel 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

![SQL Table](img/e1cf4ef1a7f5301ee63ded4806461cb2.jpg)

SQL Table

要创建这些表,您可以在 GUI 中手动进行操作或使用以下脚本:

```py
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('system.db')

with con:

    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
    cur.execute("INSERT INTO Users VALUES(2,'Howard')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")

    cur.execute("CREATE TABLE Jobs(Id INT, Uid INT, Profession TEXT)")
    cur.execute("INSERT INTO Jobs VALUES(1,1,'Scientist')")
    cur.execute("INSERT INTO Jobs VALUES(2,2,'Marketeer')")
    cur.execute("INSERT INTO Jobs VALUES(3,3,'Developer')")

```

W
wizardforcel 已提交
274
作业表有一个额外的参数`Uid`。 我们使用它来连接 SQL 查询中的两个表:
W
init  
wizardforcel 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

```py
SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid

```

您可以将该 SQL 查询合并到 Python 脚本中:

```py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('system.db')

with con:    

    cur = con.cursor()    
    cur.execute("SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid")

    rows = cur.fetchall()

    for row in rows:
        print row

```

它应该输出:

```py
$ python get2.py
(u'Michelle', u'Scientist')
(u'Howard', u'Marketeer')
(u'Greg', u'Developer')

```

您可能会喜欢:[数据库和数据分析](https://pythonspot.com/python-database/)