Search code examples
pythonpyqtpyqt4qsqlqueryqsqldatabase

PyQt QSqlQuery.prepare() returns false


In PyQt4 I create a QSqlDatabase like

slpath = 'path/to/my/db.sqlite'
db = QSqlDatabase.addDatabase('QSPATIALITE')
db.setDatabaseName(slpath)

This seem to work. Now I try to UPDATE a table layer_styles as follows:

query = QSqlQuery(db) #db cp. above
query.prepare("UPDATE layer_styles SET f_table_catalog=:path;")
query.bindValue(":path", slpath)
query.exec_()

But the query.prepare(...) returns false. What am I doing wrong?


Solution

  • There isn't a built-in database driver called "QSPATIALITE", but your QGIS installation may provide a custom SpatiaLite driver with that name. This driver is an extension to sqlite, so you can use it like this:

    slpath = 'path/to/my/db.sqlite'
    if QSqlDatabase.isDriverAvailable('QSPATIALITE'):
        db = QSqlDatabase.addDatabase('QSPATIALITE')
    else:
        db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName(slpath)
    if not db.open():
        print('ERROR:', db.lastError().text())
    

    If prepare() or exec_() still fail, you can use query.lastError() to check for mistakes in the sql statement.