尝试使用 Python 在 MS-Access 数据库中动态添加来自 excel 的列(字段)时出现数据类型转换错误

Data Type Conversion Error while trying to dynamically add columns(fields) from excel in MS-Access database using Python

我正在尝试将第 1 行(即列名)从 excel sheet 填充到 ms-access 数据库,但它给了我 'Data类型转换错误 (3421)'。知道为什么会这样吗?

from comtypes.client import CreateObject
from xlrd import open_workbook,cellname
import os
from comtypes.gen import Access

access = CreateObject('Access.Application')    

DBEngine = access.DBEngine

db = DBEngine.CreateDatabase('test.mdb', Access.DB_LANG_GENERAL)

excel_file = open_workbook('test_excel_file.xlsx')
work_sheet = excel_file.sheet_by_index(0)

db.BeginTrans()
db.Execute("CREATE TABLE MY_TABLE (ID Text)")

for row_index in range(0, 1):
    for col_index in range(0, work_sheet.ncols):
        cell_value = work_sheet.cell(row_index,col_index).value
        db.Execute("ALTER TABLE MY_TABLE ADD COLUMN %s", cell_value)

db.CommitTrans()
db.Close()

错误:

Traceback (most recent call last):
File "My_DB_Code.py", line 21, in <module>
db.Execute("ALTER TABLE MY_TABLE ADD COLUMN %s", cell_value)
_ctypes.COMError: (-2146824867, None, (u'Data type conversion error.', u'DAO.Dat
abase', u'jeterr40.chm', 5003421, None))

参数化查询允许用参数代替列的 ,但不能代替 table 和列名本身。您将需要为此使用字符串格式,如

db.Execute("ALTER TABLE MY_TABLE ADD COLUMN [{0}] TEXT(50)".format(cell_value))