【问题标题】:How to update an MS Access table which contains auto-number columns from a pandas df?如何更新包含来自 pandas df 的自动编号列的 MS Access 表?
【发布时间】:2019-04-29 14:30:44
【问题描述】:

我需要使用 pandas df 在 MS Access 中填充一个表。此表包括一个自动编号列和另一个默认值为 =now() 的列。

我尝试传递以下数据框,将 ID 和 RowInsertedTime 列保持为空白,但这没有成功。

d = {'ID': ['',''], 'col1': [1, 2], 'col2': [3, 4], 'RowInsertedTime': ['','']}
df = pd.DataFrame(data=d)

我使用 pyodbc 库执行了我的代码,如下所示:

connection_string = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
    r'DBQ=C:\Users\Public\MyTest.accdb;'
)
cnxn = pyodbc.connect(connection_string, autocommit=True)
crsr = cnxn.cursor()

# insert the rows from the DataFrame into the Access table    
crsr.executemany(
    f"INSERT INTO [{table_name}] (ID, col1, col2, RowInsertedTime) VALUES (?, ?, ?, ?)",
    df.itertuples(index=False))

不幸的是,这将返回以下错误:

DataError: ('22018', '[22018] [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression. (-3030) (SQLExecDirectW)')

知道如何获取 MS Access 表中显示的空白字段的自动值吗?

【问题讨论】:

标签: pandas ms-access pyodbc


【解决方案1】:

您必须忽略不更新的列。

crsr.executemany(
    f"INSERT INTO [{table_name}] (col1, col2) VALUES (?, ?)",
    df.itertuples(index=False))

访问将填补空白。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2018-11-25
    • 2020-04-18
    相关资源
    最近更新 更多