1

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jochen Schwarze
  • 292
  • 6
  • 27

1 Answers1

3

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • At least from inside PyQGIS QSPATIALITE works fine, even if not in the standard drivers. I got this from the answer to this post https://gis.stackexchange.com/questions/167707/connecting-qgis-spatialite-and-python I simply forgot `db.open()`... – Jochen Schwarze Mar 05 '18 at 09:49
  • @JochenSchwarze. Thanks. I did suspect it may be a custom driver, but for some reason I could not find any information about it, so I drew the wrong conclusions. I have amended my answer accordingly. – ekhumoro Mar 05 '18 at 18:02