代码之家  ›  专栏  ›  技术社区  ›  theGtknerd

将PostgreSQL行强制转换为文本,但保持列分开

  •  1
  • theGtknerd  · 技术社区  · 6 年前

    我正在使用Python开发Postgres查看器。我需要将所有列转换为文本,以便在GUI中显示它们。我不知道每个表有多少列或者它们的名称,因为这应该是一个通用的查看器。谷歌给了我这个代码:

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

    但是,这会像这样连接行:

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

    SELECT * 做:

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

    Edit2:我需要光标.说明(),因此无法使用t.*::text。

    1 回复  |  直到 6 年前
        1
  •  0
  •   theGtknerd    6 年前

    好吧,@Jon Clements提供的一个解决方案是:

     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)
    

    我的最终解决方案是:

    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)
    

    将空字符串转换为 '' None 价值观。我的代码实际上更广泛,因为它需要创建treeview列等等。希望这能帮助将来来这里的人。