简体   繁体   English

如何使用 psycopg2 查询 postgres-db 视图?

[英]How do I query a postgres-db view with psycopg2?

I've got psycopg2 running and I can successfully query tables of my database.我已经运行了psycopg2 ,我可以成功查询我的数据库表。 This is a working example of querying the table my_table :这是查询表my_table的工作示例:

import psycopg2
try:
  conn_string="dbname='my_dbname' user='user' host='localhost' password='password'"
  print "Connecting to database\n->%s" % (conn_string)

  conn = psycopg2.connect(conn_string)
  print "connection succeeded"
except:
  print "no connection to db"

cur = conn.cursor()

try:
  cur.execute(""" SELECT *  from my_table; """)

  records = cur.fetchall()
  cur.close()

except:
  print "Query not possible"  

Question: How can I query a view, let it be called my_view , within the same database my_dbname ?问:我如何可以查询视图,让它被称为my_view ,同一个数据库中my_dbname

The same way you'd query a table.与查询表的方式相同。 From a SELECT point of view, a VIEW is the exact same thing as a TABLE :SELECT角度来看, VIEWTABLE完全相同:

cur.execute("SELECT * from my_view")

Note that you generally do not want to use a black except: .请注意,您通常希望使用黑色except: Catch a specific exception if you have to, but you are usually better off not catching the exception at all rather than block all feedback on errors as you've done here.如果必须的话,捕获一个特定的异常,但通常最好根本不捕获异常而不是像这里所做的那样阻止对错误的所有反馈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM