SQL psycopg2 insert variable that is a list of variable length into database

Question:

I am trying to write a row of observations into my database, but I have some unique variable called list_variable which is a list of strings that can be of length 1-3. So sometimes [‘string1’] but sometimes also [‘string1′,’string2’] or [‘string1′,’string2′,’string3’].

When I try to add this to my database by:

def add_to_cockroach_db():
        cur.execute(f"""
        INSERT INTO database (a, b, c)
        VALUES ({time.time()}, {event},{list_variable};  <--- this one
        """)
        conn.commit()

I would get the following error (values have been changed for readability):

SyntaxError: at or near "[": syntax error
DETAIL:  source SQL:
INSERT INTO database (a, b, c)
        VALUES (a_value, b_value, ['c_value_1', 'c_value_2'])
                                  ^
HINT:  try h VALUES

It seems that having a variable that is a list is not allowed, how could I make this work out?

Thanks in advance!

**edit

list_variable looks e.g., like this = [‘value1′,’value2’]

Asked By: intStdu

||

Answers:

You can either cast it to string using

str(['c_value_1', 'c_value_2'])

which looks like this:

"['c_value_1', 'c_value_2']"

or join the elements of your list with a delimiter you choose. This for example generates a comma separated string.

",".join(['c_value_1', 'c_value_2'])

which looks like this:

'c_value_1,c_value_2'

Like Maurice Meyer has already pointed out in the comments, it is better to pass your values as a list or as a tuple instead of formatting the query yourself.
Your command could look like this depending on the solution you choose:

cur.execute("INSERT INTO database (a, b, c) VALUES (%s, %s, %s)", (time.time(), event, ",".join(list_variable)))
Answered By: bitflip
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.