简体   繁体   English

从 Pandas DataFrame 插入 Access 数据库

[英]INSERT INTO Access database from pandas DataFrame

Please could somebody tell me how should look like insert into the database but of the all data frame in python?请有人告诉我应该如何插入数据库但是python中的所有数据框?

I found this but don't know how to insert all data frame called test_data with two figures: ID, Employee_id.我找到了这个,但不知道如何插入所有名为 test_data 的数据框,其中包含两个数字:ID、Employee_id。

I also don't know how to insert the next value for ID (something like nextval)我也不知道如何为 ID 插入下一个值(类似于 nextval)

Thank you谢谢

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

Update, June 2020: 2020 年 6 月更新:

Now that the sqlalchemy-access dialect has been revived the best solution would be to use pandas' to_sql method.现在sqlalchemy-access方言已经恢复,最好的解决方案是使用 pandas 的to_sql方法。

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


(previous answer) (之前的回答)

You can use pyodbc's executemany method, passing the rows using pandas' itertuples method:您可以使用 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))

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.更新:像这样的参数化查询再次使用 pyodbc 版本 4.0.27 但不是 4.0.25(如上所述)或 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 .这个问题在这里讨论https://github.com/mkleehammer/pyodbc/issues/509

Using to_sql you may do :使用to_sql你可以这样做:

test_data.to_sql('employee_table', engine, index=False, if_exists='append')

This will add the values of the test_data at the end of your employee table.这将在您的员工表的末尾添加 test_data 的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM