SQL: How to insert a new record in a QSqlRelationalTableModel
-
Hi! I modified the master/detail (Music Archive) project in Qt creator's examples by using a localhost's MySQL database.
Now, inserting of a new record in artistModel (that is a QSqlTableModel) is always successful, and i can see the new record inserted trough phpMyAdmin().
@int Dialog::addNewArtist(const QString &name)
{
QSqlTableModel *artistModel = model->relationModel(2);
QSqlRecord record;int id = generateArtistId(); QSqlField f1("id", QVariant::Int); QSqlField f2("artist", QVariant::String); QSqlField f3("albumcount", QVariant::Int); f1.setValue(QVariant(id)); f2.setValue(QVariant(name)); f3.setValue(QVariant(0)); record.append(f1); record.append(f2); record.append(f3); artistModel->insertRecord(-1, record); return id;
}@
But _ insertRecord()_ function doesn't work with the Album Model (model), that is a QSqlRelationalTableModel:
@int Dialog::addNewAlbum(const QString &title, int artistId)
{
int id = generateAlbumId();
QSqlRecord record;QSqlField f1("albumid", QVariant::Int); QSqlField f2("title", QVariant::String); QSqlField f3("artistid", QVariant::Int); QSqlField f4("year", QVariant::Int); f1.setValue(QVariant(id)); f2.setValue(QVariant(title)); f3.setValue(QVariant(artistId)); f4.setValue(QVariant(yearEditor->value())); record.append(f1); record.append(f2); record.append(f3); record.append(f4);
if( model->insertRecord(-1, record))
qDebug()<<"ROW INSERTED";
else qDebug()<<"FAIL!"; // always returns FAIL!
return id;
}@So how i can insert a new record in a QSqlRelationalTableModel, using a MySql db?
Thanks a lot
-
Hi Pavlon,
maybe you should use insertRowIntoTable ( const QSqlRecord & values ).Regards,
Sven -
Hi Sven, thanks for your reply. Your function is a virtual function, so I should re-implement it?
Working on my problem I noticed that the above function works if Submit() button call only one of them. If both function were called in sequence, the first one works fine but the second one fails
-
You don't need to reimplement this function, but you can if you need it.
Maybe you have to call submit() before inserting the next row.