Skip to main content
 首页 » 编程设计

python之从 pandas DataFrame 插入 Access 数据库

2025年05月04日22jiqing9006

有人能告诉我在 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() 

请您参考如下方法:

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)) 

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