You can call open inside the same if(), or after the whole if/else block.

There is no point in calling open() before it is valid and there is no point in passing the instance to QSqlQuery before it is opened.

There is also no point in using prepare if you are still just concenating strings instead of passing the msg value as via bindValue().

You also might want to think what your while loop is doing, in particular the life time of the "model" object and which class you are in.

Cheers,
_