Python更新数据库数据的三种方式(update+replace)

方式一:更新 update

python 复制代码
#!/usr/bin/env python
# coding=utf-8

import pymysql


# Python 连接MySQL-本地测试
def main():
    # 1.设置连接
    db = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='123456',
        db='test',
        charset='utf8')
    #2. 游标
    cursor = db.cursor()
    # 3.写sql语句
    sql = "update test.user set name='吴老师' where age=26"

    #4. 解析sql语句
    cursor.execute(sql)
    # 5.提交
    db.commit()

if __name__ == '__main__':
    main()

方式二:追加 insert into

python 复制代码
#!/usr/bin/env 
# coding=utf-8

import pymysql
# Python 连接MySQL-本地测试
def main():
    # 1.设置连接
    db = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='123456',
        db='test',
        charset='utf8')
    #2. 游标
    cursor = db.cursor()
    # 3.写sql语句
    sql = "INSERT INTO user (name,age)VALUES('Jack','150')"
    #4. 解析sql语句
    cursor.execute(sql)
    # 5.提交
    db.commit()

if __name__ == '__main__':
    main()

方式三:存在的数据-更新;新增数据-追加 repalce into

python 复制代码
#!/usr/bin/env 
# coding=utf-8

import pymysql
# Python 连接MySQL-本地测试
def main():
    # 1.设置连接
    db = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='123456',
        db='test',
        charset='utf8')
    #2. 游标
    cursor = db.cursor()
    # 3.写sql语句
  	list1 = []
   # 列表同时添加多个值,结果为列表
  	list1.extend([imsi,twoLevelCustId,twoLevelCustName, iccid, operatorsId, operatorsName, msisdn,tradeId,apnName,apnState,totalFlow,poolId,insert_time])
	sql_insert = "replace into test.simcard_lenovo_life_cycle_dtl(imsi,twoLevelCustId, twoLevelCustName, iccid, operatorsId,operatorsName,msisdn,tradeId,apnName,apnState,totalFlow,poolId,insert_time)value(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    #4. 解析sql语句
    cursor.execute(sql_insert,list1)
    # 5.提交
    db.commit()
   
if __name__ == '__main__':
    main()
注:replace into方式用之前,需要设置数据库表中字段有唯一键,或者为唯一索引。否则依然是insert into 追加。(例如设置ICCID为主键后,表中已有iccid数据会进行数据更新)
相关推荐
用户298698530141 分钟前
Python 一键导出 Excel 中的图表和形状为图片
后端·python·excel
汤米粥5 分钟前
Python爬虫——json解析
爬虫·python·json
王九思8 分钟前
对称加密与非对称加密详解
java·网络·数据库
周杰伦的稻香10 分钟前
(1071, ‘Specified key was too long; max key length is 767 bytes‘)
数据库·mysql
lxysbly13 分钟前
Android PS3模拟器下载推荐2026|安卓PS3模拟器哪个好?手机玩PS3游戏指南
android·游戏·智能手机
武陵悭臾20 分钟前
Python应用开发学习:如何让随机数按一定比列出现
python·学习·random·概率·随机数
Leo.yuan25 分钟前
数据目录和数据字典有什么区别?一文讲清
大数据·数据库·人工智能
全堆鸿蒙27 分钟前
鸿蒙应用开发实战【37】— 数据统计:countByStatus 聚合查询
数据库·华为·harmonyos·鸿蒙系统
惜分飞29 分钟前
记录block 0损坏,数据文件大量坏块,使用不当数据库版本恢复等各种操作之后的故障处理---惜分飞
数据库·block0损坏·ora-17503
qq_2468397533 分钟前
记一次 Flutter 预热帧引起的初始化问题
android·flutter