zehpunktbarron
zehpunktbarron

Reputation: 1223

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

I've got psycopg2 running and I can successfully query tables of my database. This is a working example of querying the 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?

Upvotes: 2

Views: 5354

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

The same way you'd query a table. From a SELECT point of view, a VIEW is the exact same thing as a TABLE:

cur.execute("SELECT * from my_view")

Note that you generally do not want to use a black 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.

Upvotes: 3

Related Questions