1

我使用下面的脚本成功更新了 Access .mdb 数据库中的文本字段字段。我正在尝试更新数字类型字段,但出现错误。

import csv, pypyodbc
conn=pypyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=c:/MDBTest/MyReducedMdb.mdb;')
cursor=conn.cursor()
LUT = {}
with open("C:\MDBTest\order.txt") as file:
    for line in file:
        (key, val) = line.split()
        LUT [key] = val
print (LUT)
cursor.execute("select * from Components")
rows = cursor.fetchall()
for row in rows:
    warehousecode=row[6].strip()
    if warehousecode in LUT:
        cursor.execute("""
                        UPDATE Components
                        SET Order=?
                        Where [Component Key]=?;""", (int(LUT[warehousecode]), str(row[0])))
        cursor.commit()

当我运行代码时,出现以下错误。

{'406-007': '2', '406-012': '4', '406-005': '1', '406-015': '5', '406-010': '3'}
Traceback (most recent call last):
  File "D:\My Python\Scripts\IrricadDatabaseOrderUpdate.py", line 18, in <module>
    Where [Component Key]=?;""", (int(LUT[warehousecode]), str(row[0])))
  File "C:\Python34\lib\pypyodbc.py", line 1596, in execute
    check_success(self, ret)
  File "C:\Python34\lib\pypyodbc.py", line 986, in check_success
    ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
  File "C:\Python34\lib\pypyodbc.py", line 954, in ctrl_err
    raise ProgrammingError(state,err_text)
pypyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.')
>>>

请让我知道您认为问题可能出在哪里。谢谢。

4

1 回答 1

1

您的问题是这ORDER是一个保留的 SQL 关键字。将其括在引号中,以避免您的 SQL 驱动程序感到困惑。

"""
    UPDATE Components
    SET "Order"=?
    Where [Component Key]=?;"""

并让您的 DB 设计人员能够使用 SQL 关键字作为列名。

于 2016-06-09T23:10:57.823 回答