Python 使用 PyMySQL 操作 Mysql 数据库
下载
1 | $ sudo pip install PyMySQL |
连接数据库
1 | #!/usr/bin/env python |
使用 URI 创建连接
创建连接非常简单,但是配置在项目中却不方便,如果数据信息使用 URI 就简单了很多,这需要 urllib
模块的配合1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
import pymysql.cursors
from urllib.parse import urlparse
URI = 'mysql+pymysql://root:wxnacy@127.0.0.1:3306/study?charset=utf8mb4'
URL_CONFIG = urlparse(URI)
conn = pymysql.connect(
host = URL_CONFIG.hostname,
port = URL_CONFIG.port,
user = URL_CONFIG.username,
password = URL_CONFIG.password,
db = URL_CONFIG.path[1:],
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor
)
注意地址模式需要使用 mysql+pymysql
操作数据库
插入数据
1 | cursor = conn.cursor() |
查询数据
1 | cursor = conn.cursor() |
完整 demo
1 | #!/usr/bin/env python |
