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

Python新手求助:如何在SQL请求中使用外部文件及传感器数据?

解决从外部导入值并在SQL查询中使用的问题

Hey Brian, let's fix your code so you can use external values (from your Stamdata module and the DS18B20 sensor) in your SQL query safely and easily. Here's how to do it step by step:

1. 替换SQL中的硬编码值'1.5'为Varmekurve的值

You already have K = Varmekurve set up, so we can use that variable directly. But never concatenate variables directly into SQL strings (this causes SQL injection risks). Instead, use parameterized queries.

2. 读取DS18B20传感器的温度数据

We'll create a simple function to read the sensor's data file, parse the temperature value, and convert it to a usable number.

3. 整合所有内容到安全的SQL查询中

Use MySQLdb's parameter placeholder %s to pass your dynamic values into the query.

修改后的完整代码

#!/usr/bin/env python
import MySQLdb
from Stamdata import Varmekurve

# 读取DS18B20传感器温度的函数
def read_ds18b20_temp(sensor_path):
    try:
        with open(sensor_path, 'r') as f:
            lines = f.readlines()
            # 找到包含温度值的行(以't='开头的部分)
            temp_line = [line for line in lines if 't=' in line][0]
            temp_raw = temp_line.split('t=')[1].strip()
            # 转换为摄氏度(原始值是千分之一度)
            temp_celsius = float(temp_raw) / 1000.0
            # 可以根据需求取整或者保留小数,比如取整数
            return int(temp_celsius)
    except Exception as e:
        print(f"读取传感器失败: {e}")
        return None

# 初始化变量
kurvenummer = Varmekurve  # 从Stamdata导入的Varmekurve值
sensor_path = '/sys/bus/w1/devices/28-0316007914ff/w1_slave'
temp_sensor = read_ds18b20_temp(sensor_path)

# 如果传感器读取成功,执行SQL查询
if temp_sensor is not None:
    # 打开数据库连接
    db = MySQLdb.connect("localhost","root","Codename","MyDvoDb")
    # 创建游标对象
    cursor = db.cursor()
    
    # 使用参数化查询,%s是占位符,会自动处理类型和转义
    sql = "SELECT SetTemp FROM varmekurver WHERE kurvenummer = %s AND TempSensor = %s"
    # 传入参数元组,顺序对应占位符
    cursor.execute(sql, (kurvenummer, temp_sensor))
    
    results = cursor.fetchall()
    for row in results:
        print(f"获取到的SetTemp值: {row[0]}")
    
    # 关闭连接
    db.close()
else:
    print("无法获取传感器温度,终止操作")

关键说明:

  • 参数化查询:用%s作为占位符,然后把变量放在元组里传给cursor.execute(),这是MySQLdb推荐的安全方式,能避免SQL注入,同时自动处理数据类型转换。
  • 传感器读取函数:read_ds18b20_temp函数负责读取传感器文件,解析出温度值。如果读取失败(比如文件不存在或权限问题),会返回None,避免后续代码出错。
  • 代码结构:我们把传感器读取和数据库操作分开,让代码更清晰易维护。

后续控制阀门的思路(提前给你参考)

当你拿到SetTemp和当前传感器温度后,可以判断两者的差值:

# 假设已经获取到SetTemp和当前温度current_temp
set_temp = row[0]
current_temp = temp_sensor
temperature_diff = abs(current_temp - set_temp)

if temperature_diff >= 3:
    # 温度差超过3度,执行打开/关闭阀门的操作
    print("需要调整阀门")
    # 这里添加控制电动阀的代码
elif temperature_diff <= 2:
    # 温度差在允许范围内,保持当前状态
    print("温度正常,无需调整")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:59:18