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()
相关推荐
guts35021 小时前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集
森林猿21 小时前
java-modbus-读取-modbus4j
java·网络·python
2401_8796938721 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
chushiyunen1 天前
python chatTts实现tts文本转语音、音频
python
FreakStudio1 天前
把 Flask 搬进 ESP32,高中生自研嵌入式 Web 框架 MicroFlask !
python·单片机·嵌入式·cortex-m3·异步编程·电子diy
love530love1 天前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
chushiyunen1 天前
python中的内置属性 todo
开发语言·javascript·python
2301_793804691 天前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
Hommy881 天前
【开源剪映小助手】IPC 通信机制
python·开源·aigc·剪映小助手
Zhansiqi1 天前
dayy43
pytorch·python·深度学习