QSqlTableModel empty result
If I do this:
QSqlQuery searchQuery(QString("select * from people where id = %1").arg(1));
if (searchQuery.next())
{
std::cout << "Name: " << searchQuery.value(1).toString().toStdString() << std::endl;
}
The output is (as expected):
Name: David
However, if I do this:
QSqlTableModel *model = new QSqlTableModel;
// Set used table
model->setTable("people");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
// Set where clause
model->setFilter(QString("id=%1").arg(1));
model->select();
// Read result
QSqlRecord record = model->record();
if (!record.isEmpty())
{
std::cout << "Name from model: " << record.value(1).toString().toStdString();
}
The record is not empty, but the output is blank:
Name from model:
Can anyone see what have I done wrong using the QSqlTableModel?
Also, with both methods, I don't understand how you don't have to tell it which database to use (i.e. I instantiate a QSqlDatabase and .open() it, but I never开发者_如何转开发 tell the query to operate on the database?)
Thanks,
David
QSqlRecord record = model->record();
You are using QSqlQueryModel::record() which returns a "blank" record, instead of QSqlQueryModel::record(int row). The record you are getting is not empty : you can get the number and name of fields returned by the query from it.
With QSqlQuery or QSqlTableModel, you can specify which database connection to use (see QSqlTableModel or QSqlQuery constructors). If you don't, then the default database connection is used : see QSqlDatabase documentation. If you didn't explicitly gave it a name, the connection you opened is the default connection.
精彩评论