Python模块--PyMySQL(八)

  • 时间:2025-10-27 23:25 作者: 来源: 阅读:0
  • 扫一扫,手机访问
摘要:一、PyMySQL简介 PyMySQL : 是封装了MySQL驱动的Python驱动,一个能使Python连接到MySQL的库。 文档:https://github.com/chendemo12/knowledgegraph/wiki/pymysql%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3 源码地址:https://githu

一、PyMySQL简介

PyMySQL : 是封装了MySQL驱动的Python驱动,一个能使Python连接到MySQL的库。
文档:https://github.com/chendemo12/knowledgegraph/wiki/pymysql%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3
源码地址:https://github.com/PyMySQL/PyMySQL
模块地址:https://pypi.org/project/PyMySQL/

二、模块安装

pip install PyMySQL
或
pip install PyMySQL==0.9.3

三、连接数据库

1. 创建表

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `email` varchar(255) COLLATE utf8_bin NOT NULL,
    `password` varchar(255) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
AUTO_INCREMENT=1 ;

四、增删改查

1. 添加数据

# coding=utf-8
import pymysql

conn=pymysql.connect("localhost","root","1234","qt_db", cursorclass=pymysql.cursors.DictCursor)
# 增
cursor=conn.cursor()
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql,( admin@qq.com , 123456 ))
conn.commit()
conn.close()

2. 查询

# coding=utf-8
import pymysql

conn=pymysql.connect("localhost","root","1234","qt_db", cursorclass=pymysql.cursors.DictCursor)
# 创建对象
cursor=conn.cursor()
sql="select * from users where email like %s"
cursor.execute(sql, %ad% )
# 数据提取
result=cursor.fetchone()
# result=cursor.fetchall()
print(result)
conn.close()

说明:
fetchone(): 查询一条
fetchall():查询所有
cursor.fetchmany(10):提取指定10条记录

3. 修改

# coding=utf-8
import pymysql

conn=pymysql.connect("localhost","root","1234","qt_db", cursorclass=pymysql.cursors.DictCursor)
# 创建cursor对象
cursor=conn.cursor()
# 修改数据
sql="update users set email=%s,password=%s where id=%s"
cursor.execute(sql,("system@163.com","000000",1))
conn.commit()
conn.close()

4. 删除数据

# coding=utf-8
import pymysql

conn=pymysql.connect("localhost","root","1234","qt_db", cursorclass=pymysql.cursors.DictCursor)
# 创建cursor对象
cursor=conn.cursor()
# 删除
sql="delete from users where id=%s"
cursor.execute(sql,(1))
conn.commit()
conn.close()

  • 全部评论(0)
最新发布的资讯信息
【系统环境|】pymysql使用(2025-10-27 23:27)
【系统环境|】如何使用Python和pymysql库连接数据库(2025-10-27 23:26)
【系统环境|】Python模块--PyMySQL(八)(2025-10-27 23:25)
【系统环境|】属性、正则表达式、pymysql、多线程编程(2025-10-27 23:24)
【系统环境|】一文讲完pymysql:python操作Mysql数据库(2025-10-27 23:23)
【系统环境|】Django使用上下文语句调用pymysql(2025-10-27 23:22)
【系统环境|】Python3.8 SQLAlchemy 和 PyMySQL 区别(2025-10-27 23:21)
【系统环境|】探讨NewSQL数据库在高并发场景下的ACID特性保障机制与实现策略(2025-10-27 23:21)
【系统环境|】MySQL 事务管理: ACID 特性实现原理(2025-10-27 23:20)
【系统环境|】数据库事务控制: 实现ACID特性及隔离级别调优(2025-10-27 23:19)
手机二维码手机访问领取大礼包
返回顶部