0

I am making a user management system using PyQT4 + PostgreSQL 9.1. While writing the following code for establishing connection with the database, i get syntax error :-

from PyQt4 import QtSql, QtGui , QtCore
import _sha256
import psycopg2


def createConnection(): 

    QSqlDatabase db = QSqlDatabase.addDatabase("QPSQL"); 
    db.setDatabaseName("mysite");
    db.setUserName("postgres");
    db.setPassword("password");
    db.setHostName("localhost");
    bool ok = db.open();
    if not db.open():
        QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"),
                QtGui.qApp.tr("Unable to establish a database connection.\n"
                              "This example needs PostgreSQL support."),
                QtGui.QMessageBox.Cancel)
        return False

    query = QtSql.QSqlQuery()
    query.exec_("create table usermanagement(ID int primary key,"
                "userid int,firstname varchar(20), lastname varchar(20),usertype varchar(15),password varchar(20),)")
    query.exec_("insert into usermanagement values(1, 'Danny','Boyle','normaluser','normaluser')")

    return True

The error message is as follows:-

QSqlDatabase db = QSqlDatabase.addDatabase("QPSQL"); ^ SyntaxError: invalid syntax

1 Answer 1

1

You can't declare variable types in Python; a classname followed by a space followed by a variable name is not Python syntax.

Just do db = QSqlDatabase.addDatabase("QPSQL").

(You have the same problem at bool ok = ...)

Your code also doesn't define QSqlDatabase anywhere to begin with; presumably you mean to import it from somewhere.

Also remove all of the semicolons from your code; they're not required as statement terminators in Python and are considered bad style.

Sign up to request clarification or add additional context in comments.

2 Comments

i don't get any errors after making the above changes.However, the table does not get created in PostgreSQL when i run the python file.
db = QtSql.QSqlDatabase.addDatabase("QPSQL") db.setDatabaseName("mysite") db.setUserName("postgres") db.setPassword("password") db.setHostName("localhost") ok = db.open()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.