Python向Mysql增加数据

本文介绍了如何在Python中使用pymysql模块进行DML操作,包括插入单条和多条数据,并强调了手动提交事务的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三 Python增加数据

image-20220302152816937

注意

在python的pymysql模块,如果需要操作DML语句,需要手动提交事务con.commit()

3.1 插入单挑数据

import pymysql

def add_one():
    # 链接数据库
    con = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test', charset='utf8')
    # 获取操作数据的对象 cursor
    cursor = con.cursor()
    # 编写SQL-DML
    sql = "INSERT INTO product VALUES (0,%s,%s,%s,%s);"
    agrs = (('华为6', 2200, 4, '高端6'))
    # 执行SQL
    cursor.executemany(sql, agrs)
    # 提交事务
    con.commit()
    # 关闭Cursor
    cursor.close()
    # 关闭链接
    con.close()
if __name__ == '__main__':
    add_one()


3.2 插入多条数据

import pymysql

def add_many():
    # 链接数据库
    con = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test', charset='utf8')
    # 获取操作数据的对象 cursor
    cursor = con.cursor()
    # 编写SQL-DML
    sql = "INSERT INTO product VALUES (0,%s,%s,%s,%s);"
    agrs = ((('华为6', 2200, 4, '高端6'), ('华为7', 2200, 4, '高端7')))
    # 执行SQL
    cursor.executemany(sql, agrs)
    # 提交事务
    con.commit()
    # 关闭Cursor
    cursor.close()
    # 关闭链接
    con.close()
if __name__ == '__main__':
    add_many()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留不住的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值