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数据会进行数据更新)
相关推荐
CarIise24 分钟前
MySQL数据库表关系与多表查询:从表间关系设计到JOIN联表查询
数据库·mysql
2601_9620990829 分钟前
replit如何运行python
python·代码编辑器·编程环境·在线ide·replit
头发够用的程序员31 分钟前
别被 TOPS 参数迷惑:手把手推导边缘 GPU 整型算力
人工智能·python·ubuntu·计算机视觉·硬件架构·边缘计算
网络工程小王39 分钟前
【LLM开发实验】FastAPI 学习笔记
数据库·笔记·学习·mysql·fastapi
TechWayfarer1 小时前
做IP归属地查询时总是查不准?IP纯净度检测实战:从“查归属地“到识别“脏IP“的四个维度
服务器·网络·python·tcp/ip·安全·web安全
Aime_Perfect1 小时前
sqlserver always on
服务器·数据库·sqlserver
摘星编程1 小时前
从“数据出库“到“模型入库“:DolphinDB 库内机器学习全流程实践
数据库
你的坚定1 小时前
SurfaceFlinger合成一帧的完整流程
android
小溪学编程1 小时前
Java InputStream 详解:从基础到实战
java·python·php
Sagittarius_A*1 小时前
【好靶场】SQL注入-时间盲注
数据库·sql