Question

Is it possible to get the number of records in a table after QtSql.QSqlTableModel.setTable(tableName) and before QtSql.QSqlTableModel.select()? Qt documentation about setTable function says:

Sets the database table on which the model operates to tableName. Does not select data from the table, but fetches its field information.

So these are my questions :) Which field information? Does it contain the number of records? How to access it if necessary? (I would like to display a progress bar while the table is being loaded)

Était-ce utile?

La solution

After calling setTable you can get the number of fields, field names and the number of records of your table via QSqlQuery objects by issuing SQL commands, for instance:

model = QSqlTableModel(db=your_db)
model.setTable("your_table")
...
query = QSqlQuery("SELECT column_name FROM information_schema.columns WHERE table_name='your_table'")
query.next()
print query.numRowsAffected() # print the number of fields
query.previous()
while query.next():
    print query.value(0).toString()  # print the field name

will print the number of fields the table "your_table" and the field names.

For getting the number of rows without populating your model you can use a COUNT command as follows:

query = QSqlQuery("SELECT COUNT(*) FROM your_table")
query.next()
print query.value(0).toString()  # print the number of records
print model.rowCount()  # print 0 as the model has not been populated yet

I thought that COUNT(1) performs better than COUNT(*) but it seems to be a myth (see this SO question).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top