How to use Python 2.7 to connect to Postgres  db?

Posted on 2012-03-14
Last Modified: 2012-03-16

I would like to use Python272 to connect to a Postgres db. I found instructions here:   to createa database etc. I looked at the directions and downloaded DB-API, psycopg2 modules. Then I used the Python interperator to enter
Python DB-API:

import psycopg2 as dbapi2
db = dbapi2.connect (database="python", user="python", password="python")
cur = db.cursor()

I get a Syntax error: invalid syntax at
cur = db.cursor()
**screen shot attached.

I really don't understand how I could attach to the database....I have not created the db yet in the directions...but this is how the directions seem to read - in order.
Question by:MissyMadi2
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
LVL 29

Accepted Solution

pepr earned 500 total points
ID: 37723674
You have probably already found it, but you have missing closing parenthesis on the line with

db = dbapi2.connect (...

at the screen shot.

Author Comment

ID: 37724787
Thanks....second pair of eyes always helps :)

I'm still not sure if I'm using the Python interperator correctly for the commands for DB-API2.0.  From the instructions , I am to run these commands from the Python interperator??
LVL 29

Expert Comment

ID: 37724869
I am sorry, I cannot help with PostgreSQL and its interface from Python.  Probably someone else will help you here.  If not, send a request for the attention to the topic-area administrator.
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

LVL 29

Expert Comment

ID: 37724916
But yes, you are expected to put the SQL command string into your cur.execute() as shown at the page:

cur.execute ("""CREATE TABLE versions (released date, version varchar, status varchar)""")

Open in new window

The triple quotes are used here to suggest that you can use the multiline string for the purpose (the SQL command may look more readable), like this:

cur.execute ("""CREATE TABLE versions (
                   released date, 
                   version varchar, 
                   status varchar

Open in new window

Here the CREATE TABLE does not fill the cur object with loopable information, but for example:

cur.execute ("SELECT * FROM versions")

Open in new window

makes the cur object be accessor to he data retrieved from the database.  (It seems the interface to PostgreSQL is at least similar to other database interfaces...)

rows = cur.fetchall()                 # here you get the list of rows
for i, row in enumerate(rows):
    print "Row", i, "value = ", row

Open in new window

If the interface was modernized, you can also try:

for i, row in enumerate(cur):
    print "Row", i, "value = ", row

Open in new window

without using the .fetchall().  It is because the cur often works as the iterator object.
LVL 29

Expert Comment

ID: 37724941
Thanks for the points but you can usually be a bit slower in accepting, and discuss the problem more thoroughly also with other people who probably looked at your question but did not reacted yet (waiting where the discussion goes ;)

You can still add your comments here and it is likely it can be answered even after accepting (if it is related to the question).

Author Comment

ID: 37725139
OK. I thought I may have to open another question.

Using the mentioned URL to do the examples, I entered the SQL commands directly from the SQL Query, all data was created and retrieved, etc.  Simple....

I don't understand the DB-API2.0 side of this. I use the Python Interperator and enter cur.execute ("SELECT * FROM versions");

Shouldn't I see all records returned in the Pthyon Interperator screen?
LVL 29

Expert Comment

ID: 37725200
Yes, if the table "versions" is there, if it contains anything, and if no error happened.  Try to replace the for loop by simply printing the result of .fetchall():

rows = cur.fetchall()
print rows

Open in new window

When working in the interactive mode, you can use simply:

>>> rows

Open in new window

instead of print rows

Author Comment

ID: 37725323
Got it!! Thanks. Rows returned in Python. I think what happened is that my connection timed out??

My goal is to create a GUI for users to enter data and capture data and store it. We are currently performing manually and storing data in spreadsheets. Now I can apply the DB-API 20 code to gain access to the Postgres db.

How do I get to the GUI creation for the users? A form for the users to fill out to capture the data?
LVL 29

Expert Comment

ID: 37728221
For GUI, you have to choose one of the more possibilities. I recommend to focus on the cross-platform frameworks.  I tend to use the free software (another criterium).

Python comes with TkInter (the wrapper around the rather ol Tcl/Tk,  The cons is that the windows do not look natural (native) in the chosen OS.

I personally like WxPython, which is the wrapper around wxWidgets (, You can get the advertised book [a.k.a. wxBook] also for free in PDF, legally).  The cons is that it there is no version for Python 3, yet.

There also is PyQt which is the wrapper around Qt framework (,  The cons is more complex licensing.  I cannot speak for that.

If you never programmed a GUI application, you should be prepared to spend some time when learning the chosen GUI framework.

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Whats the correct entry into pg_hba.conf  file 12 108
python question 5 85
Path to Python 9 139
Reading text file in Python gives strange results 7 101
Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

697 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question