PyMySQL
PyMySQL是基于python连接操作mysql库的第三方库
- 介绍:代码托管地址:https://github.com/PyMySQL/PyMySQL
- 在线文档:https://pymysql.readthedocs.io/en/latest/index.html
安装
python3 -m pip install PyMySQL
环境要求
- Python – one of the following:
- MySQL Server – one of the following:
示例
可以使用分步式的写法,创建连接,创建游标,执行语句,关闭游标,关闭连接的方式,使用mysql数据库。
但是不建议这样做,建议使用关键字with使用PyMySQL操作mysql数据库:
1 import pymysql.cursors 2 3 # Connect to the database 4 connection = pymysql.connect(host=‘localhost‘, 5 user=‘user‘, 6 password=‘passwd‘, 7 database=‘db‘, 8 charset=‘utf8mb4‘, 9 cursorclass=pymysql.cursors.DictCursor) 10 11 with connection: 12 with connection.cursor() as cursor: 13 # Create a new record 14 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" 15 cursor.execute(sql, (‘webmaster@python.org‘, ‘very-secret‘)) 16 17 # connection is not autocommit by default. So you must commit to save 18 # your changes. 19 connection.commit() 20 21 with connection.cursor() as cursor: 22 # Read a single record 23 sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" 24 cursor.execute(sql, (‘webmaster@python.org‘,)) 25 result = cursor.fetchone() 26 print(result)
实战:
待补充:......
参考:
https://github.com/chendemo12/knowledgegraph/wiki/pymysql%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3
https://pymysql.readthedocs.io/en/latest/index.html