请能有人告诉我应该怎么看起来像插入到数据库中,但在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()
您可以使用pyodbc的executemany
方法,通过利用大熊猫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。尝试使用这些版本将导致错误的“不implimented可选功能”。这个问题在这里讨论https://github.com/mkleehammer/pyodbc/issues/509。
使用to_sql
你可以这样做:
test_data.to_sql('employee_table', conn, if_exists='append')
这会在你的职员表的末尾添加TEST_DATA的值。