6

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

  • 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
8

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.

  • 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
3

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

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

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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