PDA

View Full Version : QSqlQuery problem.



coding_neo
18th October 2011, 12:58
Hello :

I have the following code which connects to the Mysql database and attempts to do an insert.




#include <QApplication>
#include <QtSql/qsqldatabase>
#include <QtSql/qsqlquery>
# include <QMessageBox>
# include <QString>
# include <QVariant>

class Person
{
public:
QString *fname;
QString *lname;
QString *mobile;
Person()
{
this->fname = new QString();
this->lname = new QString();
this->mobile = new QString();
};
};




int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("demo");
db.setUserName("root");
db.setPassword("root");
if(!db.open())
{
QMessageBox *m = new QMessageBox();
m->setText("Failure Connecting to Database");
m->show();
}
else
{
QMessageBox *m = new QMessageBox();
m->setText("Successful connection");
m->show();
}

Person *p = new Person();
p->fname->append("John");
p->lname->append("Smith");
p->mobile->append("9980324083");

QSqlQuery mQuery(db);
mQuery.prepare("INSERT INTO PERSON (id,first_name,last_name,phone) VALUES (?,?,?,?)");
mQuery.addBindValue(QVariant("NULL"));
mQuery.addBindValue(QVariant(*(p->fname))) ;
mQuery.addBindValue(QVariant(*(p->lname)));
mQuery.addBindValue(QVariant(*(p->mobile)));
mQuery.exec();

return a.exec();
}


It corresponds to the following schema in mysql database:


CREATE DATABASE DEMO
CREATE TABLE PERSON
( id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(255),
last_name VARCHAR(255),
mobile_phone VARCHAR(255) );

The code compiles, links and runs fine (along with showing a successfull connection to the database) but I dont see the inserted values in the database.
So for example when I go to the command line interface and type the following at the mysql command prompt:



use demo;
select * from person;


I get an empty set.

What am I doing wrong?

norobro
18th October 2011, 15:46
Put a qDebug() statement in your code after the prepare statement to check for errors:
qDebug() << mQuery.lastError(); Or check your field names.

cincirin
18th October 2011, 21:49
mQuery.prepare("INSERT INTO PERSON (first_name, last_name, mobile_phone) VALUES (?,?,?)");

ChrisW67
19th October 2011, 02:49
More than likely your query is failing because you try to insert NULL into a not null id column but it could be any number of other things. Check the return value of the exec() call and if it is false look at lastError().

You could also save yourself a bunch of awkward syntax and memory leaks (Person has no destructor releasing resources) by storing actual QStrings in Person and not pointers.