#!/usr/bin/env python3
import psycopg2
if __name__ == '__main__':
DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
column_names = []
with psycopg2.connect(DSN) as connection:
with connection.cursor() as cursor:
cursor.execute("select column_name from information_schema.columns where table_schema = 'YOUR_SCHEMA_NAME' and table_name='YOUR_TABLE_NAME'")
column_names = [row[0] for row in cursor]
print("Column names: {}\n".format(column_names))
要在与数据行相同的查询中获取列名,可以使用光标的描述字段:
#!/usr/bin/env python3
import psycopg2
if __name__ == '__main__':
DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
column_names = []
data_rows = []
with psycopg2.connect(DSN) as connection:
with connection.cursor() as cursor:
cursor.execute("select field1, field2, fieldn from table1")
column_names = [desc[0] for desc in cursor.description]
for row in cursor:
data_rows.append(row)
print("Column names: {}\n".format(column_names))
来自Mark Lutz的“编程Python”:
要在单独的查询中获取列名,可以查询information\u schema.columns表
要在与数据行相同的查询中获取列名,可以使用光标的描述字段:
您可以做的另一件事是创建一个游标,您可以使用该游标按列的名称引用列(这是一种需要,让我首先进入本页):
相关问题 更多 >
编程相关推荐