Python 格式化表中的数组数据
数据以以下格式显示:Python 格式化表中的数组数据,python,postgresql,Python,Postgresql,数据以以下格式显示: tags_list = [ ['foo'], ['foo', 'boo', 'goo'], ['boo', 'zoo'] ] 我正在将这些数据写入表: for tags in tags_list: cursor.execute("""INSERT INTO tags_table VALUES (%s);""", (tags,)) 但这样表中的数据就变成了类型元组: (['foo'],) (['foo', 'boo', 'goo'],) (
tags_list = [
['foo'],
['foo', 'boo', 'goo'],
['boo', 'zoo']
]
我正在将这些数据写入表:
for tags in tags_list:
cursor.execute("""INSERT INTO tags_table VALUES (%s);""", (tags,))
但这样表中的数据就变成了类型元组:
(['foo'],)
(['foo', 'boo', 'goo'],)
(['boo', 'zoo'],)
在我期待的时候:
{'foo'}
{'foo', 'boo', 'goo'}
{'boo', 'zoo'}
是否可以将数据转换为普通PostgreSQL的数组视图?我只需按以下方法创建一个表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()
这是我的工作!我猜你没有提交你的游标或者你的字段类型不对
回到您的示例,我创建了一个与您类似的表:
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)
我真的不明白为什么需要将结果显示为{}
,但是有一种简单的方法可以通过声明自己的列表
类型来实现
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}
以下是一些折衷方案:
cursor.execute("""SELECT * FROM tags_table;""")
rows = cursor.fetchall()
for row in rows:
print(row[0])
“\”(ツ) _ / “传递标签
而不是(标签,)
。您能把表结构放在这里吗~@c?”ᴏʟᴅsᴘᴇᴇᴅ 然后我将得到一个异常在字符串格式化过程中并非所有参数都被转换您可以更改插入表中的值对我来说毫无意义。这是如何工作的?您甚至没有指定任何列名称。我看不出这是如何工作的。@FrankAK表只包含一列文本[],用于测试当我在python脚本中检查表时,表中的数据类型是tuple
是,python显示列表带有()
但pg显示列表带有{}
。这很酷,但问题是如何在python中修复该行为))@AntoshaShmonoff嘿,正如您所期望的结果,您可能期望使用python将其转换为pg样式,使用python非常容易,但您应该知道python将用于设置类型,而且您是对的,集合没有索引,因此无法转换为postgres数组