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()  # 关闭数据库连接
相关推荐
Olamyh5 分钟前
【 超越 ReAct:手搓 Plan-and-Execute (Planner) Agent】
python·ai
猫头虎6 分钟前
基于信创openEuler系统安装部署OpenTeleDB开源数据库的实战教程
数据库·redis·sql·mysql·开源·nosql·database
deepxuan6 分钟前
Day7--python
开发语言·python
曲幽16 分钟前
FastAPI不止于API:手把手教你用Jinja2打造动态Web页面
python·fastapi·backend·jinja2·full stack·template engine·web development
Nandeska16 分钟前
17、MySQL InnoDB ReplicaSet
数据库·mysql
禹凕21 分钟前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
Ulyanov24 分钟前
基于Pymunk物理引擎的2D坦克对战游戏开发
python·游戏·pygame·pymunk
铉铉这波能秀25 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
hlABgYML28 分钟前
基于NGSIM数据的Wiedemann99跟驰模型标定
mysql
程序媛徐师姐41 分钟前
Python基于爬虫的网络小说数据分析系统【附源码、文档说明】
爬虫·python·python爬虫·网络小说数据分析系统·pytho网络小说数据分析系统·python爬虫网络小说·python爬虫的网络小说数据