gpt4 book ai didi

python - psycopg2:在连接到 PostgreSQL 的 Python 中显示多列数据时出错

转载 作者:行者123 更新时间:2023-11-29 13:36:55 25 4
gpt4 key购买 nike

我正在使用 psycopg2 连接到 Postgres 数据库并使用 Python 在屏幕上返回查询结果。我只能返回一列数据,不像 PSQL 那样返回很多列。请看我的代码。我哪里做错了?

非常感谢您的友好回复。

#!/usr/bin/python


import psycopg2

CONNSTR = """
host=localhost
dbname=wa
user=super
password=test
port=5432"""
cxn = psycopg2.connect(CONNSTR)
cur = cxn.cursor()
cur.execute("""SELECT procpid,usename,current_query FROM pg_stat_activity;""")

rows = cur.fetchall()

print "\nShow me the query results:\n"
for row in rows:
print " ", row[1]

最佳答案

我在 initd.org/psycopg/docs/cursor.html 上找到了答案。这是正确的代码。请查看带有更改的最后两行代码。

为澄清起见,第一个版本的代码仅返回一列数据。下面列出的第二个版本将返回,实际上它将显示/打印我选择的所有列。

#!/usr/bin/python

import psycopg2

CONNSTR = """
host=localhost
dbname=wa
user=super
password=test
port=5432"""
cxn = psycopg2.connect(CONNSTR)
cur = cxn.cursor()
cur.execute("""SELECT procpid,usename,current_query FROM pg_stat_activity;""")

for rows in cur:
print rows

关于python - psycopg2:在连接到 PostgreSQL 的 Python 中显示多列数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com