Problem with QSqlQuery and duplicate entry
Hi guys:
I'm having a problem with QSqlQuery. I'm trying to insert a record to a database, like this:
Code:
Q_CHECK_PTR(driver);
/* Here I fill the record with values */
QString smt
= driver
->sqlStatement
(QSqlDriver::InsertStatement, tableName, record,
false);
if (!query.exec())
{
QMessageBox::critical(this, qApp
->applicationName
(), tr
("Error inserting into database. %1").
arg(query.
lastError().
text()));
return;
}
Ok, the problem is that I get always a duplicate entry error: "Duplicate entry '47552' for key 'id' QMYSQL: Unable the execute query", but I'm sure that value doesn't exist. In fact, the record is inserted when query.exec() is executed (but I get the error anyways). The number differs everytime in +1 ('cause I'm getting it with a max(id)+1 query).
The primary key isn't autoincremental.
Any ideas?
Thanks!!
Re: Problem with QSqlQuery and duplicate entry
It's an interesting way to insert values into a table.
Did you try to use bindings instead?
Re: Problem with QSqlQuery and duplicate entry
Though your query is highly unconventional the problem arises because the query is executed twice.
Once in the constructor and once with the exec().
This is how to execute just once:
Code:
Q_CHECK_PTR(driver);
/* Here I fill the record with values */
QString smt
= driver
->sqlStatement
(QSqlDriver::InsertStatement, tableName, record,
false);
if (!query.exec(smt))
{
QMessageBox::critical(this, qApp
->applicationName
(), tr
("Error inserting into database. %1").
arg(query.
lastError().
text()));
return;
}
or
Code:
if (!query.isValid()) .......
Re: Problem with QSqlQuery and duplicate entry
spirit: I want to make it this way to don't have to worry if I change the type of the database :) (it doesn't happen very often, but...)
Rhayader: that's it, thanks! I used this method for long time ago and never have any problem until now, that's why I didn't realize about the constructor...
Thank you guys :)
Re: Problem with QSqlQuery and duplicate entry
Quote:
Originally Posted by
Pit
spirit: I want to make it this way to don't have to worry if I change the type of the database :) (it doesn't happen very often, but...)
Don't get how it can impact when a database is changed?
Re: Problem with QSqlQuery and duplicate entry
Quote:
Originally Posted by
spirit
Don't get how it can impact when a database is changed?
If database changes maybe the INSERT statement changes with it. Like this I don't have to worry about that, I just fill the record and get the insert statement asociated to that record.
Well, is just a way, I'm not saying is the best :)