Using The SQL Model Classes
Using The SQL Model Classes
In addition to QSqlQuery , Qt offers three higher-level classes for accessing databases. These
classes are QSqlQueryModel , QSqlTableModel , and QSqlRelationalTableModel .
Example:
model = QSqlQueryModel()
model.setQuery("SELECT * FROM employee")
for i in range(model.rowCount()):
_id = model.record(i).value("id")
name = model.record(i).value("name")
print _id, name
After setting the query using setQuery() , you can use record (int) to access the individual
records. You can also use data() and any of the other functions inherited
from QAbstractItemModel .
There’s also a setQuery() overload that takes a QSqlQuery object and operates on its result set.
This enables you to use any features of QSqlQuery to set up the query (e.g., prepared queries).
Example:
model = QSqlTableModel()
model.setTable("employee")
model.setFilter("salary > 50000")
model.setSort(2, Qt.DescendingOrder)
model.select()
for i in range(model.rowCount()):
name = model.record(i).value("name")
salary = model.record(i).value("salary")
print "%s: %d" % (name, salary)
QSqlTableModel is a high-level alternative to QSqlQuery for navigating and modifying individual
SQL tables. It typically results in less code and requires no knowledge of SQL syntax.
Use record() to retrieve a row in the table, and setRecord() to modify the row. For example, the
following code will increase every employee’s salary by 10 per cent:
for i in range(model.rowCount()):
record = model.record(i)
salary = record.value("salary")
salary *= 1.1
record.setValue("salary", salary)
model.setRecord(i, record)
model.submitAll()
You can also use data() and setData() , which are inherited from QAbstractItemModel , to access
the data. For example, here’s how to update a record using setData() :
model.setData(model.index(row, column), 75000)
model.submitAll()
If you modify a primary key, the record might slip through your fingers while you are trying
to populate it.