如何将sql varchar数组转换为Python列表



我正在使用psycopg2与Python2.7中的PostgreSQL数据库进行交互。

psycopg2首先在varchar字段中将列表保存在数据库中,然后我只需要返回相同的Python列表。

插入:

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()

在pgAdmin中,它看起来像:{value,second_value}

然后我尝试做这样的事情:

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

我已经找到了可能的解决方案,但我不知道如何在我的代码中实现它。

那么,如何从sql ARRAY类型中检索回Python List?

给定:

CREATE TABLE pgarray ( x text[] );
INSERT INTO pgarray(x) VALUES (ARRAY['ab','cd','ef']);

然后psycopg2将为您处理阵列拆包。观察:

>>> import psycopg2
>>> conn = psycopg2.connect('dbname=regress')
>>> curs = conn.cursor()
>>> curs.execute('SELECT x FROM pgarray;')
>>> row = curs.fetchone()
>>> row
(['ab', 'cd', 'ef'],)
>>> row[0][0]
'ab'
>>> print( ', '.join(row[0]))
ab, cd, ef

psycopg2已经为你做到了这一点。如果 PostgreSQL 列类型是一个文本数组,即 text[],你应该得到一个 python 字符串列表。只需尝试访问查询返回的第一项,而不是整个结果元组:

for row in cursor:
    for data_item in row[0]:
    # Note the index '0' ^ here.
        print data_item

最新更新