文章目录
PyMySQL
PyMySQL概述
PyMySQL是一个用于Python编程语言的纯Python MySQL客户端库,它实现了MySQL数据库协议的所有版本,并支持多线程应用程序和Python 3.x版本。PyMySQL遵循Python标准DB API接口,并提供了许多方便的功能,如MySQL连接池、SSL/TLS加密连接、SQL注入预防等。
GitHub:https://github.com/PyMySQL/PyMySQL
安装PyMySQL库
安装PyMySQL库
pip3 install pymysql
查看第三方包的信息
pip3 show pymysql
查看安装的第三方包列表
pip3 list
PyMySQL的基本使用
API介绍
导入PyMySQL库
import pymysql
使用PyMySQL建立与MySQL数据库的连接
pymysql.connect(参数列表)
connect_db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='demo')
获取游标对象
cursor =conn.cursor()
执行SQL语句
row_count = cursor.execute(sql)
获取查询结果集
result = cursor.fetchall()
将修改操作提交到数据库
conn.commit()
回滚数据
conn.rollback()
关闭游标
cursor.close()
关闭连接
conn.close()
查询操作
# 导包
import pymysql
# 创建数据库连接对象
# 连接数据库时,除端口参数外,其余参数都要使用字符串类型指定
# host:连接的mysql主机,如果本机是'localhost'
# port:连接的mysql主机的端口,默认是3306
# user:连接的用户名
# password:连接的密码
# database:数据库的名称
# charset:通信采用的编码方式,推荐使用utf8
connect_db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', charset='utf8', database='demo')
# 获取游标对象
# 一个数据库连接对象,可以创建多个游标对象
# 一般情况下,同一时刻,只会建立一个进行操作
# 游标对象在创建的时候,默认会开启一个事务环境
cur = connect_db.cursor()
# 写SQL语句
sql_str = '''select * from item'''
# 执行SQL语句
row_count = cur.execute(sql_str)
print(f'查询到 {row_count} 条记录')
print()
# 获取一条查询结果
result = cur.fetchone()
print(result)
print()
# 获取指定条数的记录
result = cur.fetchmany(4)
for t in result:
print(t)
print()
# 获取所有数据
result = cur.fetchall()
for t in result:
print(t)
print()
# 移动游标的属性
cur.rownumber = 0
result = cur.fetchall()
print(cur.rowcount)
for t in result:
print(t)
# 关闭游标对象
cur.close()
# 关闭数据库对象
connect_db.close()
查询到 10 条记录
(1, datetime.datetime(2022, 8, 21, 19, 31, 11), 'https:img13.360buyimg.com/n1/s450x450_jfs/t1/175088/12/11173/264547/60aa5dd6Efe2b408b/b91c5bdaf6918ffa.jpg', 4299.0, '联想京东自营旗舰店', 'i5 16G 背光键盘', ' 联想笔记本电脑 小新Air14 英特尔酷睿i5 14英寸轻薄本(i5 16G 512G 高色域 大电池)银 全面屏商务办公本 ', 'https://item.jd.com/100011483893.html')
(2, datetime.datetime(2022, 8, 21, 19, 31, 11), 'https:img13.360buyimg.com/n1/s450x450_jfs/t1/113403/25/29544/70492/6302023dE572552c8/e7c452efb3616b70.jpg', 4999.0, '联想京东自营旗舰店', 'i5 16G 背光键盘', ' 联想笔记本电脑小新Pro14 英特尔Evo平台 14英寸游戏轻薄本(标压i5 16G 512G 2.8K 90Hz护眼屏)全面屏办公本 ', 'https://item.jd.com/100014546493.html')
(3, datetime.datetime(2022, 8, 21, 19, 31, 11), 'https:img12.360buyimg.com/n1/jfs/t1/219048/2/1