1

Throughout my script I create a fairly long list that then I need to insert into my database. I want to know if there's a way to direct create a SQL statement with the contents of the array instead of overdoing something like:

cursor.execute(
            '''INSERT INTO 
                my_table 
            VALUES (%s, %s, %s, %s, %s, /* 'til almost infinity */);''', 
            (list[0], list[1], list[3]... /* again almost until infinity */))
0

2 Answers 2

2

You can use string formatting and join to achieve the VALUES expansion, using the length of your data list. You can then just use a list or tuple as is for the actual values. Something like:

cursor.execute("""INSERT INTO my_table VALUES({})""".format(','.join('%s' for x in my_list)), data)
Sign up to request clarification or add additional context in comments.

Comments

1

How about something like this:

cursor.execute(
    '''INSERT INTO 
        my_table 
    VALUES (''' + ','.join(['%s' for x in mylist]) + ''');''', 
    mylist
)

Use ','.join(['%s' for x in mylist]) to create a comma separated string of placeholders for your data.

2 Comments

I did not know you could use * in such manner. It doesn't seem to work in this context, though.
@JDGamboa how about without the *? Unfortunately, I don't have access to a PG database to test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.