You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的带占位符SQL INSERT语句中使用CASE表达式

修改后的代码实现

方式一:使用问号占位符

保持原有问号占位符风格,只需调整INSERT语句并重复传入temperature参数供CASE判断:

def insert_data(self, timestamp, temperature, humidity):
    self.cursor.execute("""
      INSERT INTO sensor_data(timestamp, temperature, humidity, freezing)
      VALUES (?,?,?, 
        CASE 
          WHEN ? <= 32 THEN 'freezing' 
          ELSE 'not freezing' 
        END
      )""", (timestamp, temperature, humidity, temperature))
    self.conn.commit()

方式二:使用命名参数(更易读)

如果你的数据库驱动支持命名参数(如SQLite、PostgreSQL),可以用这种方式避免重复传参:

def insert_data(self, timestamp, temperature, humidity):
    self.cursor.execute("""
      INSERT INTO sensor_data(timestamp, temperature, humidity, freezing)
      VALUES (:ts, :temp, :hum, 
        CASE 
          WHEN :temp <= 32 THEN 'freezing' 
          ELSE 'not freezing' 
        END
      )""", {"ts": timestamp, "temp": temperature, "hum": humidity})
    self.conn.commit()
核心说明
  • 先在INSERT INTO的目标列列表中添加freezing列,对应VALUES子句中的第四个值位置
  • CASE表达式直接在SQL中引用传入的temperature参数:
    • 问号占位符需要每个位置对应一个参数,因此要重复传入temperature
    • 命名参数允许同一参数在SQL中多次复用,代码更简洁易维护
  • 所有判断逻辑由SQL的CASE表达式完成,Python层无需额外处理温度判断逻辑

内容的提问来源于stack exchange,提问作者jerH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 22:30:32