0

I wrote the code below, but I need that the PostGIS connection to be verified, to be sure that the username and password are right. I tried this: How to access user credentials in database connection? , but it didn't worked.

I am using QGIS 3.8.3

uri = QgsDataSourceUri()
uri.setConnection('LPOSTDES-CL2', '5432', 'ugpi', None, None)
connInfo = uri.connectionInfo()
(success ,user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
    QgsCredentials.instance().put(connInfo, user, passwd)
uri.setConnection('LPOSTDES-CL2', '5432', 'ugpi', user, passwd)
  • 1
    Replace (a, user, passwd) with (success, user, passwd), it works with me. – J. Monticolo Feb 12 at 15:48
  • @J.Monticolo Thanks! Edited the post and tried again, but didn't work, because, if I enter an incorrect username or password, it doesn't return me back some error message. To see what the QGIS receive, type in the end: print(uri.connectionInfo()) – vitorcsm Feb 13 at 11:01
2

You can directly verify this with QtSql, see the following Python3 code :

from PyQt5.QtSql import QSqlDatabase

host = "LPOSTDES-CL2"
port = 5432
database = "ugpi"

db = QSqlDatabase.addDatabase("QPSQL")
db.setHostName(host)
db.setPort(port)
db.setDatabaseName(database)

(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
    db.setUserName(user)
    db.setPassword(passwd)

if db.open():
    print("Connection successful !")
else:
    print("Connection failed.")

Here I just copy the method without have connInfo and there is no really reason for use QgsCredentials here, just a dialog with two QLineEdit widgets will do the stuff.

  • Thanks, works perfectly :) – vitorcsm Feb 14 at 13:39

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.