PyMySQL
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库。PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。
安装依赖
连接开关
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', password='', database='')
db.close()
|
游标开关
cursor = db.cursor()
cursor.close()
|
执行语句
cursor.execute(sql, args=None)
cursor.executemany(sql, args)
|
获取数据
data = cursor.fetchone()
data = cursor.fetchall()
data = cursor.fetchmany(size)
|
事务处理
示例
import pymysql
db = pymysql.connect(host='localhost', user='root', password='123456', database='DBName')
cursor = db.cursor()
sql = "SELECT uid,username,password FROM `user` WHERE `gender` = %s"
try: cursor.execute(sql, ("男",)) db.commit() except: db.rollback() finally: cursor.close() db.close()
|