INSERT INTO Access database from pandas DataFrame

房东的猫 提交于 2019-12-04 20:59:51
Gord Thompson

You can use pyodbc's executemany method, passing the rows using pandas' itertuples method:

print(pyodbc.version)  ## 4.0.24 (not 4.0.25, which has a known issue with Access ODBC)
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()

# prepare test environment
table_name = "employee_table"
if list(crsr.tables(table_name)):
    crsr.execute(f"DROP TABLE [{table_name}]")
crsr.execute(f"CREATE TABLE [{table_name}] (ID COUNTER PRIMARY KEY, employee_id TEXT(25))")

# test data
df = pd.DataFrame([[1, 'employee1'], [2, 'employee2']], columns=['ID', 'employee_id'])

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

Update: Parameterized queries like this work again with pyodbc version 4.0.27 but not 4.0.25 (as mentioned above) or 4.0.26. Attempting to use these versions will result in an "Optional feature not implimented" error. This issue is discussed here https://github.com/mkleehammer/pyodbc/issues/509.

Using to_sql you may do :

test_data.to_sql('employee_table', conn, if_exists='append')

This will add the values of the test_data at the end of your employee table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!