psycopg2:在连接到 PostgreSQL 的 Python 中显示多列数据时出错
我正在使用 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]
I am using psycopg2 to connect to Postgres database and return query results on the screen using Python. I can only return one column of data, not many columns like PSQL does. Please see my code. Where did I do wrong?
Your kind response would be greatly appreciated.
#!/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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在 initd.org/psycopg/docs/cursor.html 上找到了答案。这是正确的代码。请查看最后两行代码的更改。
为了澄清起见,第一个版本的代码仅返回一列数据。下面列出的第二个版本将返回,实际上它将显示/打印我选择的所有列。
I found the answer on initd.org/psycopg/docs/cursor.html. Here is the correct code. Please see the last two lines of code with the changes.
For clarification, the first version of code only returns one column of data. The 2nd version listed below will return, actually it will display/print, all the columns I selected.
我不太清楚你想要实现什么目标。
如果您只需要一列数据,那么您可以在 SQL 查询中过滤掉该数据。例如:
psycopg2 仍然会返回一个元组数组,其中每个元组都包含您请求的列。如果您不需要元组和列数据的值数组,那么您可以使用以下方法转换它们:
如果这不是您所要求的,请重新表述您的问题。
It is not quite clear to me what you are trying to achieve.
If you only need one column of data, then you can filter that out in the SQL query. For instance:
Still psycopg2 will return an array of tuples, where each tuple contains the columns you requested for. If you do not want the tuples and just an array of values for your the column-data, then you can convert them using:
If this is not what you are asking for, please rephrase your question.