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数据会进行数据更新)
相关推荐
wxin_VXbishe1 天前
springboot在线课堂教学辅助系统-计算机毕业设计源码07741
java·c++·spring boot·python·spring·django·php
参宿四南河三1 天前
Android Compose SideEffect(副作用)实例加倍详解
android·app
dblens 数据库管理和开发工具1 天前
PostgreSQL模式:数据库中的命名空间艺术
数据库·postgresql·oracle
程序员三藏1 天前
使用Docker和Selenium构建自动化测试环境
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
CaracalTiger1 天前
本地部署 Stable Diffusion3.5!cpolar让远程访问很简单!
java·linux·运维·开发语言·python·微信·stable diffusion
火柴就是我1 天前
mmkv的 mmap 的理解
android
没有了遇见1 天前
Android之直播宽高比和相机宽高比不支持后动态获取所支持的宽高比
android
数据最前线1 天前
数据管理技术发展的3个阶段
数据库·考研·数据库系统概论
api_180079054601 天前
【技术教程】Python/Node.js 调用拼多多商品详情 API 示例详解
大数据·开发语言·python·数据挖掘·node.js
SelectDB1 天前
冷查第一,再登榜首!Apache Doris 3.1 全面刷新 JSONBench 性能纪录
数据库·apache