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数据会进行数据更新)
相关推荐
XW9632583 小时前
除湿机行业组织能力与人才地图报告
大数据·服务器·网络·数据结构·数据库·人工智能
AI创界者3 小时前
Python 进阶实战(七十一章):研发效能度量、自动化质量门禁与工程规范落地实战
人工智能·python·aigc
yingjie1103 小时前
快榜GEO|官网 AI 可读性自查 12 项(附 Python 检测脚本)
开发语言·人工智能·python
Decay__4 小时前
PostgreSQL 性能调优方法论 —— pg_stat_statements、EXPLAIN ANALYZE、瓶颈定位流程与参数基线
运维·数据库·sql·postgresql
tryCbest4 小时前
Python 爬虫扩展篇(二):验证码的检测与人工介入——把“拦路虎”当作信号,而不是要征服的对手
开发语言·爬虫·python
前端兰博6 小时前
分库分表
数据库
@陈小鱼6 小时前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
智能收银研究所7 小时前
收银系统选型对比:美团、客如云、拉卡拉、收钱吧各适合什么门店
java·前端·数据库
谙弆悕博士7 小时前
动态自适应多智能体架构的 LangGraph 实现:从元调度器到可运行原型
人工智能·python·神经网络·机器学习·架构·多智能体·智能体
七夜zippoe8 小时前
金仓 Kingbase 安装与 Java 连接(保姆级):从装库到 JDBC 跑通全记录
java·数据库·jdbc·kingbase·金仓