Home > database >  Inserting csv file into a database using Python
Inserting csv file into a database using Python

Time:11-29

In Python I've connected to a Postgres database using the following code:

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. I read the csv in as follows:

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?

CodePudding user response:

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

  • Related