使用python将pandas数据框导入MS Access表

v9tzhpje  于 2023-04-10  发布在  Python
关注(0)|答案(3)|浏览(263)

我是python的新手,正在尝试为我的工作实现一些自动化。目前,我正在尝试通过python从CSV中更新Access表。到目前为止,我已经将CSV读取到pandas dataframe中,并尝试一次添加一行到Access中。这是我到目前为止所做的:

import pandas as pd
import pypyodbc
import glob

df = pd.read_csv("data.csv", header = 0, low_memory = False)
df = df[['Description','SN','Attribute_1','Attribute_2',\
    'Attribute_3','Attribute_4','Cost','Date']]

con = pypyodbc.connect('DRIVER={Microsoft Access Driver \ 
(*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;\
PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL=MS\
Access;DriverId=25;DefaultDir= \ 
C:/Users/testuser/Documents;DBQ=C:/Users/testuser/ \ 
Documents/Python/test.mdb;')

cursor = con.cursor()

for row in df.iterrows():
    cursor.execute("INSERT INTO test.table1([Description],[SN], 
      [Attribute_1], [Attribute_2],[[Attribute_3],[Attribute_4],\
      [Cost],[Date]) values (?,?,?,?,?,?,?,?)", (row[0], row[1] ,\
      row[2], row[3], row[4], row[5], row[6], row[7]))
    con.commit()
cursor.close()
con.close()

每当我运行这个,我最终得到的错误

IndexError: tuple index out of range

我已经查找了这个问题的典型原因,据说是错误的索引(即在Python中从1而不是0开始),并确保我从0索引开始。
我也找遍了所有我能想到的关于cursor.execute命令如何工作的文档,但我仍然感到困惑,不确定我是否有正确的语法。任何帮助都将不胜感激!
样本数据:

Description   SN      Attr_1    Attr_2  Attr_3  Attr_4  Cost    Date
type_a      12938475  shiney    black    hard     a     1.09   7/20/18
type_b      18293940  matt      silver   soft     b     0.56   7/20/2018
type_d      18283940  matt      gray     soft     c     0.78   7/16/2018
type_a      18944938  shiney    silver   medium   d     3.4    7/18/2018
type_a      17485003  matt      silver   hard     v     2.3    7/17/2018
fwzugrvs

fwzugrvs1#

“我已经查找了这个问题的典型原因,据说是错误的索引(即在Python中从1而不是0开始),并确保我从0索引开始。
这也是当你超过预期的数据或当你到达文件的结尾。
给前任的。

>>t = (1,2,3)
>>t(2)
3
>>t(3)
IndexError: tuple index out of range

请检查这一点。此外,如果这不工作,请上传'data.csv'到您的驱动器,并发送共享链接,以便我们可以运行代码和测试它。

uoifb46i

uoifb46i2#

好的,假设你用Python做了一些分析,把结果保存为CSV,你想导入它,因为你有一些唯一的ID,你要Map到,对吧,就这样做。

DoCmd.TransferText acImportDelim, "", "Table1", "C:\your_path\testing.csv", True, ""
' where table1 is your table

我不认为这比这更复杂。如果我错过了重点,请回复,而你实际上是在尝试做其他事情。

lrl1mhuk

lrl1mhuk3#

自2019年9月以来,sqlalchemy-access方言已经可用。它允许我们使用pandas .to_sql()将DataFrame上传到Access。
(我是目前方言的维护者。

相关问题