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

如何将树莓派SenseHat采集的数据导入现有Azure SQL Server

树莓派SenseHat数据导入Azure SQL Server修复方案

现有代码错误原因

  • 连接超时错误:你首次使用的pymysql是MySQL专属驱动,无法兼容Azure SQL Server,数据库协议不匹配自然无法建立连接
  • 语法解析错误:两段代码末尾的sense.show_message行均缺少右括号),Python解析到文件末尾未找到配对符号就会抛出unexpected EOF while parsing报错;同时你用了MySQL专属的INSERT SET语法,且参数占位符使用了%d/%s,SQL Server不支持该写法,需改用标准语法和?占位符

前置配置要求

先在树莓派终端执行以下命令安装依赖:

sudo apt update
sudo apt install -y odbc-driver-17-for-sqlserver python3-pyodbc python3-sense-hat

同时需登录Azure门户,在SQL Server的防火墙设置中,放行你树莓派的公网出口IP,否则仍会出现连接超时问题。

修复后可直接运行的代码

import time
import pyodbc
from sense_hat import SenseHat

# 初始化SenseHat
sense = SenseHat()

# 采集传感器数据
temperature = round(sense.get_temperature(), 1)
pressure = round(sense.get_pressure(), 1)
humidity = round(sense.get_humidity(), 1)

# Azure SQL Server连接配置,请替换为你自己的配置
server = '你的服务器名.database.windows.net'
database = '你的数据库名'
username = '你的登录用户名'
password = '你的登录密码'
driver = '{ODBC Driver 17 for SQL Server}'

try:
    # 建立数据库连接
    conn = pyodbc.connect(
        f'DRIVER={driver};SERVER=tcp:{server};PORT=1433;DATABASE={database};UID={username};PWD={password}'
    )
    cursor = conn.cursor()
    # 标准SQL Server插入语法,占位符用?
    insert_sql = """
    INSERT INTO data (dat_date, dat_time, dat_temperature, dat_pressure, dat_humidity, idx_sensor)
    VALUES (?, ?, ?, ?, ?, ?)
    """
    # 按顺序传入参数
    cursor.execute(insert_sql, (
        time.strftime("%Y-%m-%d"),
        time.strftime("%H:%M:%S"),
        temperature,
        pressure,
        humidity,
        1
    ))
    conn.commit()
    cursor.close()
    conn.close()
except Exception as e:
    print(f"操作失败:{e}")

# 补全缺失的右括号
sense.show_message("T:" + str(temperature) + " P:" + str(pressure) + " H:" + str(humidity), scroll_speed=0.7)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:48:03