我在一个小型Python程序中有以下内容
def insert_data(self, timestamp, temperature, humidity):
self.cursor.execute("""
INSERT INTO sensor_data(timestamp, temperature, humidity)
VALUES (?,?,?)""",(timestamp, temperature,humidity))
self.conn.commit()
我在数据库中添加了一列名为“freezing”的列。
我想修改插入语句以使用
CASE
,这样当温度为<= 32 the freezing column gets the value "freezing" and otherwise gets "not freezing".时
我通常很清楚 CASE 语句的直接使用,但不确定它们与这样的占位符的使用。
完全披露:这是使用
CASE
语句的家庭作业的一部分。还有更多的事情,所以我并不是要求你做我的作业!但解决方案必须使用CASE
...
我认为您可以直接将 CASE 语句集成到 INSERT 查询的 VALUES 部分中,它将检查温度条件并根据您插入的温度值返回“冻结”或“不冻结”:
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()