I'm using psycopg2 for interacting with PostgreSQL database in Python2.7.
psycopg2 saves list in database at first in varchar field, and then I need simply to get the same Python list back.
Insert:
data = ['value', 'second value']
with psycopg2.connect(**DATABASE_CONFIG) as connection:
cursor = connection.cursor()
cursor.execute("INSERT INTO table_name (varchar_field) VALUES (%s)", (data)
connection.commit()
In pgAdmin it looks like: {value, second_value}
Then I tried to do something like this:
with psycopg2.connect(**DATABASE_CONFIG) as connection:
cursor = connection.cursor()
cursor.execute("SELECT varchar_field FROM table_name")
for row in cursor:
for data_item in row: # here I want to iterate through the saved list (['value', 'second_value']), but it returns string: '{value, second_value}'
print data_item
I have found possible solution, but I have no idea how to implement it in my code.
So, how can I retrieve back Python List from sql ARRAY type?
Copyright Notice:Content Author:「Dmitrijs Zubriks」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21002999/how-to-convert-sql-varchar-array-to-python-list