【问题标题】:Error Passing Variable to SQL Server Query Python将变量传递给 SQL Server 查询 Python 时出错
【发布时间】:2022-08-15 13:56:37
【问题描述】:
            cursor.execute(\"\"\" if exists ( SELECT * from Alert where alert = ? and date = ? and devicename = ? )
                BEGIN
                update Alert set alert = ? where alert = ? and date = ? and devicename = ?
                END
                ELSE
                BEGIN
                INSERT INTO Alert (alert,date,devicename) VALUES (?, ?, ?) \"\"\", row[1], row[0], filename[:-4],
                           row[1], row[1], row[0], filename[:-4], row[1], row[0], filename[:-4])
            cursor.commit()

上面的代码是我对 SQLServer 的 sql 查询。如果我更换它,它会起作用吗?有价值,但如果我这样做,我会收到错误。需要帮忙。我正在使用 pyodbc 库顺便说一句。

cursor.execute(\"\"\" if exists (SELECT * from Alert where alert = ? and date = ? and devicename = ?) pyodbc.ProgrammingError: (\'42000\', \"[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]\')\' 附近的语法不正确。(102) (SQLExecDirectW); [42000] [ Microsoft][SQL Server Native Client 11.0][SQL Server]无法准备语句。(8180)\")

    标签: python sql-server


    【解决方案1】:

    你应该通过一个元组10 个参数作为cursor#execute() 的第二个参数:

    sql =  """IF EXISTS (SELECT 1 FROM Alert WHERE alert = ? AND date = ? AND devicename = ?)
              BEGIN
                  UPDATE Alert SET alert = ? WHERE alert = ? AND date = ? AND devicename = ?
              END
              ELSE
              BEGIN
                  INSERT INTO Alert (alert, date, devicename) VALUES (?, ?, ?)
              END """
    params = (row[1], row[0], filename[:-4], row[1], row[1], row[0], filename[:-4],
              row[1], row[0], filename[:-4])
    cursor.execute(sql, params)
    

    【讨论】:

    • 嘿,我试过了,但同样的错误发生了。
    • 您还缺少插入块的END。尝试添加,q.v。我更新的答案。
    猜你喜欢
    • 2017-09-10
    • 2020-04-03
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    相关资源
    最近更新 更多