Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some questions for you:

I created a python-plugin in QGIS,

then I created a Qt gui fom my plugin

and at last I created a Postgres DB

now I need to make a connection between Qt-gui and Postgres-DB

I wrote this

 from PyQt4.QtSql import *
 db = QSqlDatabase.addDatabase("QPSQL");
 bool ok =;

but it doesn't works, I can't understand what I do wrong...

I wish someone could help me...

thank you for all! lisa

share|improve this question
check what the db.lastError() method returns – Nathan W Jul 17 '12 at 14:23
port=5432 is required even on localhost – Mapperz Jul 17 '12 at 14:34

Here is a good tutorial that helped me a lot:

update The above link has expired... :(

Here is my code that I use in my QGIS plugin:

from PyQt4.QtSql import *
db = QSqlDatabase('QPSQL')
if db.isValid():
    # string
    # string
    # string
    # string
    # integer e.g. 5432
        # assume you have a table called 'users'
        query = db.exec_("""select * from users""")
        # iterate over the rows
            record = query.record()
            # print the value of the first column
            print record.value(0) 

Hope that helps.

share|improve this answer
Can you elaborate on your answer just a little? Perhaps you could include a short summary of the main points as they relate to the question? Thanks. – WhiteboxDev Oct 1 '14 at 14:24
updated and added code snippet. – fegyi001 Oct 7 '14 at 11:56
Wonderful, thank you. – WhiteboxDev Oct 7 '14 at 12:23

I had also problems with QSqlDatabase, so I used the psycopg2 library instead:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.