首页 > 解决方案 > 如何通过外部应用(如 Python)访问 Azure-iot-edge 创建的 Docker 数据库?

问题描述

我已经从边缘设置了 Sql 模块,它将演示“tempsensor”模块中的数据存储到基于 docker 容器的 sql 数据库中。Mssql-tools-sqlcmd 可以访问数据,我可以在其中获取数据库的查询。但是当我尝试使用其他应用程序访问数据库时(我尝试过使用 python),它对我不起作用

我尝试过使用 pyodbc 但它不起作用!当我尝试安装 ODBC 驱动程序时,出现了一些超时错误。然后我尝试使用 FreeTDS 驱动程序,但这对我也不起作用。

链接 - https://docs.microsoft.com/en-us/azure/iot-edge/tutorial-store-data-sql-server

#this shows I am getting the data from the table with sql tool 

  acn-iot2@acniot2-UPC-GWS01:~$ sudo docker exec -it sql bash

root@2b08418b1986:/# /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'Strong!Passw0rd' 1> SELECT * FROM MeasurementsDB.dbo.TemperatureMeasurements 2> 去测量时间位置温度
----- --------------------------------- ----------------- --------------------------------- ----------------- ------- 2019-06-10 11:36:46.9392878 机器 21.363193834486001 2019-06-10 11:36:46.9392878 环境 20.628800209671599 2019-06-10 11:36:52.873816

#############################################################################

我用过的python代码

 import pyodbc 
  server = 'localhost,1433' 
  database = 'MeasurementsDB' 
  username = 'su' 
  password = 'Strong!Passw0rd' 
  cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL          
  Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+   
  password)
  cursor = cnxn.cursor()

我收到类似的错误

  pyodbc.OperationalError: ('HYT00', '[HYT00] [unixODBC][Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

但是当我尝试使用 python 阅读时,我无法阅读。

标签: pythondatabaseazure-iot-edge

解决方案


尽管您的代码username = 'su'在应有的位置使用username = 'sa',但我想这不是问题,因为您正在超时。

我猜您正在将容器内的数据库与在容器运行的 python 代码连接起来。

在这种情况下,您应该将您的 python 代码复制到容器中并运行,或者公开端口 1433 并连接到<container_id>:1433而不是localhost,1433


推荐阅读