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()
相关推荐
一路向阳~负责的男人5 小时前
PyTorch / CUDA 是什么?它们的关系?
人工智能·pytorch·python
aloha_7895 小时前
乐信面试准备
java·spring boot·python·面试·职场和发展·maven
火云洞红孩儿5 小时前
零基础:100个小案例玩转Python软件开发!第六节:英语教学软件
开发语言·python
2401_841495645 小时前
深度卷积生成对抗网络(DCGAN)
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·深度卷积生成对抗网络
忧郁的橙子.5 小时前
26期_01_Pyhton函数进阶
python
充值修改昵称5 小时前
数据结构基础:B+树如何优化数据库性能
数据结构·b树·python·算法
AI殉道师5 小时前
FastScheduler:让 Python 定时任务变得优雅简单
开发语言·python
小二·6 小时前
Python Web 开发进阶实战:AI 伦理审计平台 —— 在 Flask + Vue 中构建算法偏见检测与公平性评估系统
前端·人工智能·python
华研前沿标杆游学6 小时前
2026年商汤科技参访深度解析人工智能发展
python
知数SEO6 小时前
Centos如何安装高版本Python
linux·python·centos