python常识系列24-->python操作mysql之pymysql

前言

  1. pymsql是Python中操作MySQL的模块
  2. 程序在运行时,数据都是在内存中的。当程序终止时,通常需要将数据保存在磁盘上。

安装模块

python 复制代码
pip install PyMySql

基本使用

python 复制代码
## 使用 connect 函数创建连接对象,此连接对象提供关闭数据库、事务回滚等操作。
connect = pymysql.connect(host='127.0.0.1',
                     user='root',
                     password='pwd',
                     database='database_name')
# 获取游标
start = connect.cursor()
#默认获取数据的格式为元组格式

cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
#设置cursor设置为pymysql.cursors.DictCursor,可以将显示数据为 字典格式

cursor.scroll(1,mode='relative')  # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
# 第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动

# 执行sql语句
start.execute()
    # 执行单条语句
start.executemany()
    # 执行多条语句

#获取单条数据
dp = start.fetchone()

# 获取所有数据
dp = start.fetchall()

# 获取指定条数数据
dp = start.fetchone(3)
    #获取3条数据

# 关闭数据库连接
db.close()

具体实例之查询select

python 复制代码
import pymysql

# 创建数据库连接对象
connect = pymysql.connect(host='127.0.0.1',
                          user='root',
                          password='pwd',
                          database='database_name')
# 创建游标对象
cursor = connect.cursor()

table_name = 'school_info_table'
sql = "SELECT * FROM %s WHERE schoolname LIKE '%深圳%' " % table_name
try:
    cursor.execute(sql)  # 执行sql语句,也可执行数据库命令,如:show tables
    result = cursor.fetchall()  # 所有结果
    print(result)
except Exception as e:
    connect.rollback()
    print("select Fail")
    print(e)
finally:
    cursor.close()  # 关闭当前游标
    connect.close()  # 关闭数据库连接

具体实例之修改update

python 复制代码
import pymysql

# 创建数据库连接对象
connect = pymysql.connect(host='127.0.0.1',
                          user='root',
                          password='pwd',
                          database='database_name')
# 创建游标对象
cursor = connect.cursor()

table_name = 'table_name '
user_id = 'yyy'
user_no = 'xxx'
sql = "UPDATE %s SET user_no = '%s' WHERE user_id = '%s'" % (table_name, user_no, user_id)
try:
    cursor.execute(sql)  # 执行sql语句,也可执行数据库命令,如:show tables
    connect.commit()  # 增删改,必须执行事务
    print("update success")
except Exception as e:
    connect.rollback()  # 若出现失败,进行回滚
    print("update fail")
    print(e)
finally:
    cursor.close()  # 关闭当前游标
    connect.close()  # 关闭数据库连接
相关推荐
百***787513 小时前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_9421917714 小时前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python
stevenzqzq14 小时前
android mvi接口设计1
android·mvi接口设计
stevenzqzq14 小时前
android mvi接口设计2
android·mvi接口设计
忧郁的橙子.15 小时前
26期_01_Pyhton基本语法
python
sunfove15 小时前
实战篇:用 Python 徒手实现模拟退火算法解决 TSP 问题
开发语言·python·模拟退火算法
oh LAN15 小时前
提升性能:数据库与 Druid 连接池优化指南
数据库·mysql
我是菜鸟0713号16 小时前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi
我是一只小青蛙88816 小时前
TraeCNIDE Python开发全流程指南
python
欣然~16 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python