## 检查
1. 打开终端, python -V
Python 3.11.0
exit() 退回 python 交互终端
2. 打开终端, pip -V
pip 22.3 from C:\Program Files\Python311\Lib\site-packages\pip (python 3.11)
3. python 操作数据库需要扩展包 pymysql
pip install pymysql
Successfully installed pymysql-1.0.3
## 编写代码
```py
import pymysql
# 1. 链接数据库
con = pymysql.connect(
host='127.0.0.1',
user='root',
passwd='root',
port=3306
)
# 2. 获取指针、游标
cursor = con.cursor()
# 3. 准备SQL
sql = "show databases"
# 4. 执行SQL语句
# 5. 结果处理
# 5.1 对于查询类, 需要解析结果集
res = cursor.fetchall()
print(res)
for i in res:
print(i[0])
```
配置解析结果集类型为字典
```
from pymysql.cursors import DictCursor
```
```
# 1. 链接数据库
con = pymysql.connect(
host='127.0.0.1',
user='root',
passwd='root',
port=3306,
cursorclass=DictCursor
)
快速清空表中的数据
```
truncate test_no_index;
```
写如数据条数: 100000, 耗时:42.53267002105713秒
查询 耗时:0.12072563171386719秒
写如数据条数: 100000, 耗时:41.657299280166626秒
查询 耗时:0.0020720958709716797秒