【问题标题】:Inserting csv file into a database using Python使用 Python 将 csv 文件插入数据库
【发布时间】:2022-11-29 06:19:25
【问题描述】:

在 Python 中,我使用以下代码连接到 Postgres 数据库:

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

我创建了一个名为 departments 的表,并希望将数据从 CSV 文件插入到数据库中。我按如下方式读取csv:

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

我正在尝试使用以下代码将此数据插入表中:

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

我在各种文章中看到过,但我不断收到错误消息:

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

我该如何纠正这个问题,或者是否有另一种插入 csv 的方法?

【问题讨论】:

    标签: python sql psycopg2


    【解决方案1】:

    您必须将行信息作为元组传递。试试这个:

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2020-04-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      相关资源
      最近更新 更多