如何在 Python 中打印查询结果,包括列名

How to print query results in Python including column names

打印 PostgreSQL 查询结果时我只看到结果值,我想看到列名和结果值

 postgreSQL_select_Query = "SELECT epic,timestamp FROM market_data_historic s1 WHERE timestamp = (SELECT MAX(timestamp) FROM market_data_historic s2 WHERE s1.epic = s2.epic)"
    cursor.execute(postgreSQL_select_Query)
    # Close the connection
    result=(cursor.fetchall())
    for row in result:
        print (row)

这是我得到的结果:

('CC.D.LCO.USS.IP', datetime.datetime(2019, 11, 13, 22, 0))
('IX.D.DAX.DAILY.IP', datetime.datetime(2019, 7, 23, 4, 0))
('KB.D.ELECTY.DAILY.IP', datetime.datetime(2020, 1, 24, 16, 0))
('CS.D.ALUMINIUM.TODAY.IP', datetime.datetime(2019, 7, 23, 1, 0))
('CS.D.NZDCAD.TODAY.IP', datetime.datetime(2020, 1, 24, 21, 0))
('CS.D.CADCNH.TODAY.IP', datetime.datetime(2020, 1, 16, 8, 0))

我怎样才能让它变成这样:

(epic:'CC.D.LCO.USS.IP',timestamp: datetime.datetime(2019, 11, 13, 22, 0))
(epic:'IX.D.DAX.DAILY.IP',timestamp: datetime.datetime(2019, 7, 23, 4, 0))
(epic:'KB.D.ELECTY.DAILY.IP',timestamp: datetime.datetime(2020, 1, 24, 16, 0))
(epic:'CS.D.ALUMINIUM.TODAY.IP',timestamp: datetime.datetime(2019, 7, 23, 1, 0))
(epic:'CS.D.NZDCAD.TODAY.IP',timestamp: datetime.datetime(2020, 1, 24, 21, 0))
(epic:'CS.D.CADCNH.TODAY.IP',timestamp: datetime.datetime(2020, 1, 16, 8, 0))

尝试 cursordescription 属性:

Read-only attribute describing the result of a query. It is a sequence of Column instances, each one describing one result column in order. The attribute is None for operations that do not return rows or if the cursor has not had an operation invoked via the execute*() methods yet.

For compatibility with the DB-API, every object can be unpacked as a 7-items sequence: the attributes retuned this way are the following. For further details and other attributes available check the Column documentation.

  • name: the name of the column returned.
  • type_code: the PostgreSQL OID of the column.
  • display_size: the actual length of the column in bytes.
  • internal_size: the size in bytes of the column associated to this column on the server.
  • precision: total number of significant digits in columns of type NUMERIC. None for other types.
  • scale: count of decimal digits in the fractional part in columns of type NUMERIC. None for other types.
  • null_ok: always None as not easy to retrieve from the libpq.

使用 cursor.description 属性检索列名并将结果转换为字典:

result = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
for row in result:
    print (dict(zip(columns, row)))

或者,您可以使用 Real dictionary cursor or Named tuple cursor.

另见