python - 格式化表中的数组数据

标签 python postgresql

数据以以下格式呈现:

tags_list = [
    ['foo'],
    ['foo', 'boo', 'goo'],
    ['boo', 'zoo']
]

我正在将此数据写入表:

for tags in tags_list:
    cursor.execute("""INSERT INTO tags_table VALUES (%s);""", (tags,))

但是这样表中的数据变成了 tuple 类型:

(['foo'],)
(['foo', 'boo', 'goo'],)
(['boo', 'zoo'],)

在我期待的时候:

{'foo'}
{'foo', 'boo', 'goo'}
{'boo', 'zoo'}

是否可以将数据转换为普通 PostgreSQL 的 ARRAY View ?

最佳答案

我简单地按照 sql 创建了一个表:

CREATE TABLE contacts (
 id serial PRIMARY KEY,
 name VARCHAR (100),
 phones TEXT []
);

我假设您正在使用 pydb 并且我已经创建了一个如下所示的表

 id | name |    phones    
----+------+--------------
  1 |      | {123,222,33}

我的 python 代码只是简单地插入到一个列表中。

import pgdb


conn = pgdb.connect(database='test')


cur = conn.cursor()

lst = ['123','222','33']
cur.execute('insert into contacts(phones) values (%s)', (lst,))
conn.commit()

这对我有用!我猜你没有 commit 你的光标或者你的字段类型不对!

回到你的例子,我创建了一个和你一样的表:

CREATE TABLE tags_table(tags TEXT[]);

在运行我的 python 代码之前,让我们检查表。

test=# select * from tags_table;
 tags 
------
(0 rows)

和我的 python 代码:

#import pgdb
#conn = pgdb.connect(database='test')
#if psycopg2 has used
#try this 
import psycopg2
conn = psycopg2.connect(database='test')
cursor = conn.cursor()

tags_list = [
    ['foo'],
    ['foo', 'boo', 'goo'],
    ['boo', 'zoo']
]


for tags in tags_list:
    cursor.execute("""INSERT INTO tags_table(tags) VALUES (%s);""", (tags,))

conn.commit()

运行上面的代码后,我的表得到了那些结果:

test=# select * from tags_table;
     tags      
---------------
 {foo}
 {foo,boo,goo}
 {boo,zoo}
(3 rows)

我真的不明白为什么您需要将结果显示为 {},但有一种简单的方法可以通过声明您自己的 List 类型来实现。

class MyList(list):
    def __str__(self):
        items = ','.join(self)
        return '{' +'{}'.format(items if items else '') + '}'
    def __repr__(self):
        return self.__str__()


for i in d:
    j = MyList(i[0])
    print j

你会得到如下所示的结果!

{foo}
{foo,boo,goo}
{boo,zoo}
{foo}
{foo,boo,goo}
{boo,zoo}

关于python - 格式化表中的数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47806836/

相关文章:

python - 如何在 matplotlib pyplot 中将标签添加到 y 轴的区间组?

postgresql - 如何使用 Spring JpaRepository 转义问号 (?) 字符

python - 使用 pandas read_csv 时将分隔符限制为仅某些选项卡

python - 无法解析 Google Play 应用评分数据

python - 如果 Dataframe 中的数据属于同一流,如何对它们进行分组?

php - PDO inTransaction() 在数据库异常后返回 false

sql - 如何根据日期获取一个月中的天数?

python - 快速检查大型数据库的编辑距离相似性

sql - 在Postgres中,如何获得具有最大值的子分组?

postgresql 处理空值