Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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");
 db.setHostName("localhost");
 db.setDatabaseName("siti");
 db.setUserName("postgres");
 db.setPassword("bina");
 bool ok = db.open();

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
3  
check what the db.lastError() method returns –  Nathan W Jul 17 '12 at 14:23
1  
port=5432 is required even on localhost –  Mapperz Jul 17 '12 at 14:34

2 Answers 2

Here is a good tutorial that helped me a lot:

http://pythongisbook.com/blog/2013/04/11/creating-a-postgresql-connection-from-a-qgis-layer-datasource/

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
    db.setHostName('your_host')
    # string
    db.setDatabaseName('your_database_name')
    # string
    db.setUserName('your_username')
    # string
    db.setPassword('your_password')
    # integer e.g. 5432
    db.setPort('your_host')
    if db.open():
        # assume you have a table called 'users'
        query = db.exec_("""select * from users""")
        # iterate over the rows
        while query.next(): 
            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 at 14:24
    
updated and added code snippet. –  fegyi001 Oct 7 at 11:56
    
Wonderful, thank you. –  WhiteboxDev Oct 7 at 12:23

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

http://wiki.postgresql.org/wiki/Psycopg2_Tutorial

share|improve this answer

Your Answer

 
discard

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.