Python使用pymysql执行DML语句

先创建连接

复制代码
import pymysql

connection = None

try:
    # 建立数据库连接
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='root',
        database='mydatabase',
        autocommit=True #设置自动提交
    )

    #游标对象
    cursor = connection.cursor()


except Exception as e:
    print(e)
finally:
    if connection:
        connection.close()

执行select查询操作

复制代码
    #执行查询语句
    cursor.execute('select * from users')

    #获取查询的所有结果
    result = cursor.fetchall()
    print(result,type(result)) #  <class 'tuple'>

    for row in result:
        print(row)

执行insert插入操作

执行修改操作,需要通过Connection对象调用commit()方法确认提交,或者构造方法里面,autocommit设置Ture,自动提交

复制代码
    #执行插入操作
    cursor.execute("insert into users values (null,'王五','wangwu@163.com',25,now(),'13664447879')")
    #获取主键
    print("主键id=",connection.insert_id()) #主键id= 3
    #确认提交
    connection.commit()


  #设置自动提交

    # 建立数据库连接
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='root',
        database='mydatabase',
        autocommit=True #设置自动提交
    )
    
      #执行插入操作
    cursor.execute("insert into users values (null,'赵六','zhaoliu@163.com',25,now(),'13664447879')")
    #获取主键
    print("主键id=",connection.insert_id()) #主键id= 3
    # #确认提交
    # connection.commit()

执行update操作

执行update操作,与insert操作类似

复制代码
    #执行update更新操作
    cursor.execute("update users set age = 20 where id = 3 ")
    # #确认提交
    # connection.commit()

执行delete操作

复制代码
    #执行delete更新操作
    cursor.execute("delete from users where id = 3 ")
    # #确认提交
    # connection.commit()
相关推荐
电子云与长程纠缠6 分钟前
UE5制作六边形包裹球体效果
开发语言·python·ue5
DFT计算杂谈15 分钟前
KPROJ编译教程
java·前端·python·算法·conda
念恒123061 小时前
Python(循环中断)
开发语言·python
tsfy20031 小时前
Python 处理中文文件名的3个坑(附 Flask 上传解决函数)
开发语言·python·flask·文件上传·中文编码
AI技术控1 小时前
KV Cache 缓存机制的原理和应用:从 Transformer 推理到大模型服务优化
人工智能·python·深度学习·缓存·自然语言处理·transformer
vx-程序开发2 小时前
基于机器学习的动漫可视化系统的设计与实现-计算机毕业设计源码08339
java·c++·spring boot·python·spring·django·php
爱睡懒觉的焦糖玛奇朵2 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具Video To YOLO Dataset】
人工智能·python·学习·yolo·音视频
石榴树下的七彩鱼2 小时前
医疗票据 OCR 识别 API 多场景落地指南:医保结算 + 商保理赔 + 医疗信息化(附 Python/Java 完整示例)
java·python·ocr·石榴智能·医疗票据ocr·医保结算·ocrapi
idingzhi3 小时前
A股量化策略日报(2026年05月22日)
android·开发语言·python·kotlin
song5013 小时前
多卡训练加速:HCCL 集合通信实战
分布式·python·flutter·ci/cd·分类