使用字符串变量通过 pyodbc 编写 SQL 查询

问题描述 投票:0回答:1

我正在尝试使用 pyodbc 编写一个函数来编写 sql 更新。我正在格式化字符串并将其放入名为查询的变量中并尝试执行它。它执行了,但出现错误。

(我更新的表名是之前的)

def update_rocap(labview, saleno):

    #imports required modules
    import pyodbc as pyodbc
    import library

    #create connection string
    conn_str = (
        r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
        r"DBQ=path;"
        )

    #connect to database
    cnxn = pyodbc.connect(conn_str)
    crsr = cnxn.cursor()

    query = '"UPDATE before set '
    
    for i in range(0, len(labview)):
        query = query + library.update_fields[i] + ' = ' + labview[i] + ', '
    query = query[:-2]
    query = query + ' where SONo = ' + saleno + ' "'

    print(query)

    crsr.execute(query)

我需要能够将查询构建到字符串中。这是我在字符串中写入的结果查询:

"UPDATE before set SnugTension1 = SnugTension1, Tension1 = Tension1, Rotation1 = Rotation1, Torgue1 = Torgue1, RotationLB1 = RotationLB1, FinalSatus1 = FinalSatus1, SnugTension2 = SnugTension2, Tension2 = Tension2, Rotation2 = Rotation2, Torgue2 = Torgue2, RotationLB2 = RotationLB2, FinalSatus2 = FinalSatus2, SnugTension3 = SnugTension3, Tension3 = Tension3, Rotation3 = Rotation3, Torgue3 = Torgue3, RotationLB3 = RotationLB3, FinalSatus3 = FinalSatus3, SnugTension4 = SnugTension4, Tension4 = Tension4, Rotation4 = Rotation4, Torgue4 = Torgue4, RotationLB4 = RotationLB4, FinalSatus4 = FinalSatus4, SnugTension5 = SnugTension5, Tension5 = Tension5, Rotation5 = Rotation5, Torgue5 = Torgue5, RotationLB5 = RotationLB5, FinalSatus5 = FinalSatus5 where SONo = sono2 "

但是我在 crsr.execute() 上收到此错误:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] 无效的 SQL 语句;应为 'DELETE'、'INSERT'、'PROCEDURE'、'SELECT' 或 'UPDATE'。( -3500) (SQLExecDirectW)")

python sql ms-access pyodbc
1个回答
0
投票

看起来您正在将列更新为其名称。尝试类似的事情

SET
finalStatus = 'SomeNewValue'
WHERE SONo = sono2

也许这个问题是相似的并且可以提供帮助

© www.soinside.com 2019 - 2024. All rights reserved.