Heath
Heath

Reputation: 173

How to use psycopg2 to insert a list of lists

I'm using python 3.6, psycopg2 to insert data into a postgresql (9.6) database. Here is my code:

def postgre_save():
    params = Config()
    with psycopg2.connect(**params) as conn:
        cur = conn.cursor()
        lst2 = []
        lst2.append([9999, datetime.date(2017, 5, 1), 0.99, 1, 3])
        lst2.append([9999, datetime.date(2017, 6, 1), 1.2, 1, 3])
        qry = 'INSERT INTO oww.welldep(well_id, dep_date, depletion, reach, type) VALUES (%s, %s, %s, %s, %s);'
        cur.execute(qry, lst2)

When this is executed I receive the following error: IndexError: list index out of range.

If I shorten the list to a single entry the program executes, ie:

lst2 = [9999, datetime.date(2017, 5, 1), 0.99, 1, 3]

but the real list will have thousands of lists within the list. Any help is greatly appreciated. Thanks.

Upvotes: 0

Views: 2347

Answers (1)

rd_nielsen
rd_nielsen

Reputation: 2459

Use

cur.executemany(qry, lst2)

See the documentation: https://www.psycopg.org/docs/cursor.html

Upvotes: 1

Related Questions