从 Pandas DataFrame 插入 Access 数据库

Ant*_*nts 2 python ms-access insert pyodbc pandas

请有人告诉我应该如何插入数据库但是python中的所有数据框?

我找到了这个,但不知道如何插入所有名为 test_data 的数据框,其中包含两个数字:ID、Employee_id。

我也不知道如何为 ID 插入下一个值(类似于 nextval)

谢谢

import pyodbc 
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\test_database.mdb;')
cursor = conn.cursor()  
cursor.execute('''
                INSERT INTO employee_table (ID, employee_id)
                VALUES(?????????)
              ''')
conn.commit()
Run Code Online (Sandbox Code Playgroud)

ldo*_*doe 5

使用to_sql你可以这样做:

test_data.to_sql('employee_table', engine, index=False, if_exists='append')
Run Code Online (Sandbox Code Playgroud)

这会将 test_data 的值添加到员工表的末尾。


Gor*_*son 5

2020 年 6 月更新:

现在sqlalchemy-access方言已经恢复,最好的解决方案是使用 pandas 的to_sql方法。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html


(以前的回答)

您可以使用 pyodbc 的executemany方法,使用 pandas 的itertuples方法传递行:

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))
Run Code Online (Sandbox Code Playgroud)

更新: 像这样的参数化查询再次使用 pyodbc 版本 4.0.27 但不是 4.0.25(如上所述)或 4.0.26。尝试使用这些版本将导致“可选功能未实现”错误。这个问题在这里讨论https://github.com/mkleehammer/pyodbc/issues/509