简体   繁体   English

使用 Python 将 csv 文件插入数据库

[英]Inserting csv file into a database using Python

In Python I've connected to a Postgres database using the following code:在 Python 中,我使用以下代码连接到 Postgres 数据库:

conn = psycopg2.connect(
    host = "localhost",
    port = "5432",
    database = "postgres",
    user = "postgres",
    password = "123"
)
cur = conn.cursor()

I have created a table called departments and want to insert data into the database from a CSV file.我创建了一个名为 departments 的表,并希望将数据从 CSV 文件插入到数据库中。 I read the csv in as follows:我读到的csv如下:

departments = pd.DataFrame(pd.read_csv('departments.csv'))

And I am trying to insert this data into the table with the following code:我正在尝试使用以下代码将此数据插入表中:

for row in departments.itertuples():
    cur.execute('''
                INSERT INTO departments VALUES (?,?,?)
                ''',
               row.id, row.department_name, row.annual_budget)
conn.commit()

which I've seen done in various articles but I keep getting the error:我在各种文章中看到过,但我不断收到错误消息:

TypeError: function takes at most 2 arguments (4 given)

How can I correct this, or is there another way to insert the csv?我该如何纠正这个问题,或者有其他方法可以插入 csv?

You have to pass the row information as a tuple.您必须将行信息作为元组传递。 Try this instead:试试这个:

for row in departments.itertuples():
    cur.execute('''
                INSERT INTO departments VALUES (%s, %s, %s)
                ''',
               (row.id, row.department_name, row.annual_budget))
conn.commit()

See the docs for more info: https://www.psycopg.org/docs/usage.html有关详细信息,请参阅文档: https://www.psycopg.org/docs/usage.html

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

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