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数据会进行数据更新)
相关推荐
captain3764 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
前端精髓5 小时前
结构化输出with_structured_output(抽卡)
python·langchain
小此方5 小时前
Re:Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql
xszivvvv5 小时前
Mariadb数据库frm文件异常,如何恢复数据
数据库·mariadb
smile_life_5 小时前
MySQL 设置 防止账户被暴力破解
数据库·mysql
尹人入圣6 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
ShineWinsu6 小时前
对于Qt:QRadioButton常见属性以及QButtonGroup的解析
数据库·c++·qt·microsoft·gui·qradiobutton·qbuttongroup
测试盐6 小时前
oracle数据库卡顿排查
数据库·oracle
滕州市燕猫虎计算机科技工作室个体工商户6 小时前
MySQL、MVCC、多版本并发控制
数据库·mysql·mvcc·数据库事务
明航咨询-陈老师6 小时前
ITSS运行维护服务能力成熟度认证技术纵深:标准模型、等级路径、2026审核趋势与CS/CMMI对比
服务器·数据库·cmmi