2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response. The problem I actually have has nothing to to whether I query a table or a view. The view I created within my database had an other owner (not "user" as in "conn_string"). So after changing user in "conn_string" the query works.
@C.B.: I suspected there might be something else going on but your question didn't include any detail. Updated my answer with a remark towards your exception handling, which would not have helped you diagnose this problem.
for not "swallowing" exceptions +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.