Pyodbc列名称无效

2024-10-02 20:38:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过Python发送一个SQL请求,以便查询表消息(DeviceID、CommunicationTime、Data),它托管在Azure SQL数据库上

我的代码如下:

import pyodbc

server = 'xxxxxxxxxx'
database = 'xxxxxxxxxxxx'
username = 'xxxxxxxxxx'
password = 'xxxxxxxxxx'   
driver= '{ODBC Driver 17 for SQL Server}'

device = 'D1AAAA'
msgTime = '2020-01-15'

with pyodbc.connect(f"DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password}") as conn:
        with conn.cursor() as cursor:
            cursor.execute(f"SELECT DeviceID, CommunicationTime FROM Message WHERE CommunicationTime={msgTime}") AND DeviceID={device}")
            row = cursor.fetchone()
            while row:
                print (str(row[0]) + " " + str(row[1]))
                row = cursor.fetchone()
print(row)

此代码在包含SQL请求的行上显示以下错误:

pyodbc.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'D1AAAA'. (207) (SQLExecDirectW)"

但是,如果从条件中删除AND DeviceID={device},则不会得到任何错误。有人能解释一下我为什么会犯这个错误吗


Tags: 代码sqlserverdevice错误usernamepasswordcursor