SQL很少被单独使用,通常SQL会与其他的一些语言结合使用,比如Python、Java、 C#等等。这篇文章里,我们关注如何在Python中使用SQL操作数据库。

Python中内置了SQLite3,你只需要执行

1
import sqlite3

就可以开始使用了,不需要安装任何第三方库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
db = sqlite3.connect("database.db") 
# 连接到一个现有的数据库,如果没有这个文件就创建它

cur = db.cursor()
# 创建一个cursor,才能执行SQL语句

# cur.execute(你想执行的SQL语句)
cur.execute("CREATE TABLE books ('title' TEXT NOT NULL, 'price' REAL, 'sales' INTEGER, 'category' TEXT);")
# 创建一个表

res = cur.execute("SELECT name FROM sqlite_master")
# SQLite内置了一个名叫“sqlite_master”的表,储存了所有已创建的表

print(res.fetchone())
# 输出('books',)

cur.execute("""
INSERT INTO books VALUES
('The Great Gatsby', 50.99, 4, 'Fiction'),
('The Lord of the Rings', 55.99, 3, 'Fantasy')
""")
db.commit()
# 插入两名学生
# 会自动地创建事务,无需手动加上“BEGIN TRANSACTION”
# 需要手动db.commit()


category = input("category:")
res = cur.execute("SELECT title FROM books WHERE category = ?", (category, ))
# 注意传入的第二个参数是一个元组,不能直接传category
# 请使用“?”占位符,不要使用 f"SELECT title FROM books WHERE category = {category}"或者其他任何方式
# 否则可能会受到SQL注入攻击(SQL injection attacks)
# “?”占位符会自动处理传入的字符串,防止SQL注入


# cur.executemany可以批量执行SQL语句,推荐使用executemany而不是for循环嵌套execute
cur.executemany("INSERT INTO books VALUES(?, ?, ?, ?);", data)
db.commit()

res = cur.execute('SELECT title, price FROM books')
for row in res:
print(row)
'''
输出
('The Great Gatsby', 50.99)
('The Lord of the Rings', 55.99)
('To Kill a Mockingbird', 25.99)
('Pride and Prejudice', 40.99)
('To Kill a Mockingbird', 25.99)
('Pride and Prejudice', 40.99)
('1984', 35.99)
('The Catcher in the Rye', 60.99)
('Animal Farm', 30.5)
('The Hobbit', 45.0)
'''

db.close()
# 关闭数据库连接,现在可以连接别的数据库

本文属于系列文章:SQL学习笔记