【问题标题】:How to convert sql varchar array to Python list?如何将 sql varchar 数组转换为 Python 列表?
【发布时间】:2014-01-08 17:54:15
【问题描述】:

我在 Python2.7 中使用 psycopg2 与 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

我找到了possible solution,但我不知道如何在我的代码中实现它。

那么,如何从 sql ARRAY 类型中取回 Python 列表?

【问题讨论】:

  • varchar_field 的类型是什么?我希望它是一个数组,即像varchar(4096)[] 这样的东西。如果是简单的 varchar,则数组转换将不起作用。

标签: python sql postgresql psycopg2


【解决方案1】:

给定:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 它不起作用,因为它返回字符串。在这种情况下,它将打印“{”。我知道,psycopg2 从 Python 转换为 SQL 类型,但我怀疑它是否适用于 SQL -> Python。
    • @dimazubrik 你的 Python 和 psycopg2 版本?
    • @dimazubrik 确实如此!我可以在这里看到各种问题:您使用的是非常旧的 psycopg2 版本,或者您的列的类型不正确。
    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2020-07-16
    • 2019-01-23
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多