python连接mysql
- 命令行安装模块
pip install pymysql
- 导入模块
from pymysql import *
- 也可使用 imporn pymysql
- 连接数据库
- 使用connect函数
注意: 其中charset为utf8而非习惯的utf-8conn = connect(host='localhost',port=3306,user='root',password='password',database='database',charset='utf8')
- 创建光标(cursor)
- 增删改查需要使用游标
cur = conn.cursor()
- 执行语句 cur.excute(‘sql’)
- 返回结果集数量
- 遍历查询结果
- 可使用以下函数
fetchone() fetchall() fetchmany(x)`[x为行数]`
- 关闭连接 游标
cur.close() conn.close()
- 连接数据后 使用完毕需要断开连接
- 需要先关闭游标 后关闭连接s