'How to INSERT query a list of elements in python

I have tried to query all elements from a list into an insertion query, I tried by making the list into a list of tuples and directly by adding the elements from the list. But it did not work, and I don't know the best practice for this as I am no SQL shark. I have below added the two different outputs I have before I do the query. I don't know which is easier to work with for this, but the code example is for the list of elements.

Output

['testuser', 'AskeMeyer'] 

and

[('testuser',), ('AskeMeyer',)]

Code to query

   try:
        conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USER, password=PASS, sslmode='require', sslrootcert="SSLCERTIFICATE")
        cur = conn.cursor()
        var_string = ', '.join(map(str, res))
        sql = 'INSERT INTO users_from_group(name) VALUES %s;' % var_string)
        cur.execute(sql)

error from above

Database connection failed due to syntax error at or near ")"


Solution 1:[1]

it's not the proper way to store lists. you should save it as json :

json.dumps(['testuser', 'AskeMeyer'] )

then save it

Solution 2:[2]

Try this:

var_string = '(' + ','.join(map(str, res)) + ')'
sql = 'INSERT INTO users_from_group(name) VALUES %s;' % var_string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 javadfarah
Solution 2 Abhijit Kumbhar