Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting csv file into a database using Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading