I don't think returning query objects is a good idea. Imagine that you have 10 client classes using this code and someday you need to change the database structure - now you have to go through all the client classes code and update the query access.
Better option is to directly return the data from the database, without exposing internal database structure:
class User{
public:
User
(QString name,
QString address, ...
) :_name
(name
), _address
(address
) ...
{ }
QString name
() const{ return _name;
} QString address
() const{ return _address;
} // .. other access methods
private:
...
};
User myClass::GetUser(int userId)
{
q.prepare("SELECT name,address,whatever FROM User WHERE User.ID = :userId;");
q.bindValue(":id",userId);
if (q.next()) {
return User(q.value("name").toString(), q.value("address").toString(), ...);
}
throw NoSuchUserException; //.. or another way of reporting an error
}
class User{
public:
User(QString name, QString address, ...) :_name(name), _address(address) ... {
}
QString name() const{ return _name; }
QString address() const{ return _address; }
// .. other access methods
private:
QString _name;
QString _address;
QString _whatever;
...
};
User myClass::GetUser(int userId)
{
QSqlQuery q;
q.prepare("SELECT name,address,whatever FROM User WHERE User.ID = :userId;");
q.bindValue(":id",userId);
if (q.next()) {
return User(q.value("name").toString(), q.value("address").toString(), ...);
}
throw NoSuchUserException; //.. or another way of reporting an error
}
To copy to clipboard, switch view to plain text mode
This way database access code and db structure are encapsulated and separated from the rest of the program.
Bookmarks