PDA

View Full Version : How to deal with foreign key in Qt



sjyzhxw
24th May 2012, 16:06
else
{
query->prepare ("insert into Courses values (?,?,?)");
query->bindValue (0,courseIDLine->text ());
query->bindValue (1,courseNameLine->text ());
query->bindValue (2,courseTeacherIDLine->text ());

successful=query->exec ();

}

if(successful)
{
closeInsertCourseDlg ();
}
else if(!errorMsg->isVisible ())
{
//cannot execute the statement
}


but if the SQL statement doesn't satisfy the foreign key, the program will end unexpectedly, it will not just return a false

how to change the code??

ChrisW67
25th May 2012, 01:47
You change the code is a way that fixes whatever you have done that causes it to crash. You have not told us where it crashes or what you have done to isolate it. Run the code in your debugger and read the backtrace to find the source of the problem in your code.

Qt will return false if the insert fails: it does not crash.

If I assume for a moment that your code crashes somewhere in what you have presented then it will be at line 16 where the pointer errorMsg is invalid or null. This code will only be executed if the insert fails.

sjyzhxw
25th May 2012, 07:49
Thanks a lot. It is the use of the null pointer that leads to the crash.
I didn't discover that..

Added after 36 minutes:

I got another question.


QString id=delLine->text();
bool successful=false;
if(studentRadio->isChecked()){
successful=query->exec("delete from Students where StudentID="+id);
}
else if(teacherRadio->isChecked ()){
successful=query->exec("delete from Teachers where TeacherID="+id);
}else if(courseRadio->isChecked ()){
successful=query->exec ("delete from Courses where CourseID="+id);
}
if(successful){
qDebug ()<<query->lastError ().text (); //the output is " "
delDlg->close();
}
else{
//error
}

if the id doesn't exist in the table, the value of successful will still be true.
how to detect if the id doesn't exist ?

Added after 6 minutes:

should I select first , and if query->record ().count ()!=0, delete it; otherwise set the successful false?
It seems works

ChrisW67
25th May 2012, 10:31
If the aim is that the row does not exist afterward does it matter that it did not exist beforehand? If you need an optimistic offline lock or similar pattern to handle concurrent updates then that is more involved.

Anyway, depending on the database, QSqlQuery::numRowsAffected() may tell you how many rows you actually deleted.