如何通过Python动态更新数据库表?求其他实现方式
动态更新TEMP表的替代方法
首先先提个小坑:你当前的代码里有个小错误——cur.execute(statement, ('value', 'emp1'))这里传的是字符串'value',而不是你计算的变量value,应该改成cur.execute(statement, (value, 'emp1')),不然数据库会把tax字段设成字符串'value'而不是你想要的90哦。
接下来给你几种不同场景下的动态更新方法:
1. 命名参数写法(更易读)
很多数据库驱动(比如PostgreSQL的psycopg2、Oracle的cx_Oracle)支持命名参数,不用再记参数的顺序,代码可读性更高:
value = 100 * 0.9 statement = 'update temp set tax = :tax_amount where name = :emp_name' cur.execute(statement, {'tax_amount': value, 'emp_name': 'emp1'}) con.commit()
2. 用ORM框架(大型项目首选)
如果你的项目规模不小,推荐用ORM框架(比如SQLAlchemy),不用手写原生SQL,还能自动防范SQL注入,维护起来更省心:
先定义对应数据库表的模型:
from sqlalchemy import create_engine, Column, Float, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Temp(Base): __tablename__ = 'temp' name = Column(String, primary_key=True) tax = Column(Float) # 初始化数据库连接和会话 engine = create_engine('your_database_connection_string') # 替换成你的数据库URL Session = sessionmaker(bind=engine) session = Session() # 执行更新操作 emp_record = session.query(Temp).filter(Temp.name == 'emp1').first() if emp_record: emp_record.tax = 100 * 0.9 session.commit()
3. 批量更新多条记录
如果需要一次性更新多个条目,用executemany效率更高,不用循环执行单条更新:
# 示例:更新emp1和emp2的tax值分别为90和80 update_records = [(90, 'emp1'), (80, 'emp2')] statement = 'update temp set tax = :1 where name = :2' cur.executemany(statement, update_records) con.commit()
4. 动态指定更新字段(谨慎使用)
如果连要更新的字段都是动态的(比如有时候更tax,有时候更salary),绝对不能直接把外部传入的字段名拼进SQL,必须用白名单过滤来避免SQL注入:
# 先定义允许更新的字段白名单 allowed_fields = {'tax', 'salary', 'bonus'} target_field = 'tax' # 这个是动态获取的字段名,比如从用户输入或配置来 # 先校验字段是否合法 if target_field not in allowed_fields: raise ValueError(f"不允许更新的字段:{target_field}") value = 100 * 0.9 # 字段名用白名单过滤后拼接,值还是用参数化处理 statement = f'update temp set {target_field} = :1 where name = :2' cur.execute(statement, (value, 'emp1')) con.commit()
内容的提问来源于stack exchange,提问作者SKB
相关产品推荐
相关产品推荐

