I have the following insertion code for a person table having fields( name,ipaddress ). Both are defined as type varchar.
"create table Person (name varchar(40) primary key,ipaddress varchar(40))";
QString personTableQstr =
"create table Person (name varchar(40) primary key,ipaddress varchar(40))";
To copy to clipboard, switch view to plain text mode
I am trying to insert some entries into this table using the following code -
nameQuery.prepare( "SELECT * FROM Person WHERE name=:name" );
nameQuery.bindValue( ":name",tempname1 );
nameQuery.exec();
if( !nameQuery.first() )
{
logfile.
write( QString("DB does not contain this name ...").
toAscii());
insertionQuery.prepare( "INSERT INTO person (name, ipaddress) "
"VALUES (?, ?)");
insertionQuery.bindValue(0, tempname1); //tempname1 contains name
insertionQuery.bindValue(1, tempname2); //tempname2 contains ip address
if( !insertionQuery.exec() )
{
logfile.
write( QString("\n\nInsertion of new person record failed").
toAscii());
}
}
else
{
logfile.
write( QString("\n\nName already present in DB").
toAscii());
}
QSqlQuery nameQuery;
nameQuery.prepare( "SELECT * FROM Person WHERE name=:name" );
nameQuery.bindValue( ":name",tempname1 );
nameQuery.exec();
if( !nameQuery.first() )
{
logfile.write( QString("DB does not contain this name ...").toAscii());
QSqlQuery insertionQuery;
insertionQuery.prepare( "INSERT INTO person (name, ipaddress) "
"VALUES (?, ?)");
insertionQuery.bindValue(0, tempname1); //tempname1 contains name
insertionQuery.bindValue(1, tempname2); //tempname2 contains ip address
if( !insertionQuery.exec() )
{
logfile.write( QString("\n\nInsertion of new person record failed").toAscii());
}
}
else
{
logfile.write( QString("\n\nName already present in DB").toAscii());
}
To copy to clipboard, switch view to plain text mode
I am testing this code by inserting same value ( for name & ipaddress ) twice.Basically the first time I am trying to insert it enters the if-case. But even the second time it enters the if-case, but insertion fails & prints out "
Insertion of new person record failed
". But logically the first() API of QSqlQuery should return true for the second time insertion.
Is my assumption correct ? How does this API work ?
Bookmarks