Cast a PostgreSQL row to text, but keep columns separate

守給你的承諾、 提交于 2019-12-23 04:06:00

问题


I am working on a Postgres viewer using Python. I need to convert all columns to text so I can display them in my GUI. I don't know how many columns there are per table or the names of them as this is supposed to be a generic viewer. Google got me this code:

SELECT t.*::text FROM table AS t;

However, this concatenates the row like this:

t
----------------|-------
(712,982,dfdfv)

What I need is this (with type text of course), just like a normal SELECT * does:

id  | vendor_id | vendor_barcode
----|-----------|---------------
712 | 982       | dfdfv

Edit1: I can't convert the datatypes in Python, because a None will become a 'None'.

Edit2: I need the column names from cursor.description(), so I can't use t.*::text.


回答1:


Ok, so one solution offered by @Jon Clements is:

 c = connection.cursor()
 c.execute("SELECT * FROM my_table")
 rows = (str(col) if col is not None else None for col in c.fetchall())
 for row in rows:
     print (row)

My final solution was:

c.execute("SELECT * FROM my_table LIMIT 1")
select_sql = "SELECT "
for row in c.description:
    column_name = row.name
    if type_ == 17: #binary data
        select_sql += " '<binary data>',"
    else:
        select_sql += " CASE WHEN %s::text='' THEN '''''' ELSE %s::text END," % (column_name, column_name)
select_sql = select_sql[:-1] + " FROM my_table" #remove trailing comma and add table name
c.execute(select_sql)

Which converts blank strings to '' and preserves None values. My code is actually more extensive, because it needs to create treeview columns and etc. Hopefully this helps out anyone coming here in the future.



来源:https://stackoverflow.com/questions/52151156/cast-a-postgresql-row-to-text-but-keep-columns-separate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!