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()
相关推荐
vb20081113 分钟前
基于AMQP协议模拟MQTT的发布 / 订阅主题功能
python·rabbitmq
ZhuNian的学习乐园39 分钟前
LLM对齐核心:RLHF 从基础到实践全解析
人工智能·python·算法
编程饭碗1 小时前
【Java 类的完整组成】
java·开发语言·python
DLite1 小时前
Python静态类型设计:语法割裂的槽点
开发语言·python
2501_921649491 小时前
如何获取外汇实时数据:全球货币行情对接指南
后端·python·websocket·金融·区块链
时光Autistic1 小时前
【环境配置】安装LaTeX并配置到PyCharm使用
ide·python·pycharm·latex
岁岁的O泡奶2 小时前
NSSCTF_crypto_[LitCTF 2024]common_primes
开发语言·python·算法
韩师傅2 小时前
从随叫随到到规范配送:现代物流系统与 REST API 的登场
后端·python·全栈
阿拉丁的梦2 小时前
五种翻译--mo字典翻译任何blender插件的插件
python·blender
玄同7652 小时前
Python 系统编程双雄:sys 与 os 模块深度实践指南
开发语言·数据库·人工智能·windows·笔记·python·microsoft