数据types转换错误,同时尝试使用Python从MS-Access数据库中的Excel中dynamic添加列(字段)

我试图填充第一行(即列名称)从Excel工作表到MS访问数据库,但它给了我' 数据types转换错误(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)) 

参数化查询允许使用参数replace列的 ,但不能replace表和列名称本身。 你将需要使用string格式,如

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