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()  # 关闭数据库连接
相关推荐
孟健5 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞7 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽9 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
阿巴斯甜12 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker13 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
敏编程14 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪14 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook14 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
xq952714 小时前
Andorid Google 登录接入文档
android
黄林晴15 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack