Cast a PostgreSQL row to text, but keep columns se

2019-06-08 01:19发布

问题:

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.