PDA

View Full Version : How to connect QT with MYSQL and perform opeartions like Insert,Delete,Update?



Gokulnathvc
17th June 2011, 13:59
I am using the following code: but it fails. Kindly help on this:


bool ok=false;

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("screengrabber");
db.setUserName("root");
db.setPassword("1");
ok = db.open();

cincirin
17th June 2011, 14:11
What is the result of QSqlDatabase::drivers (http://doc.qt.nokia.com/latest/qsqldatabase.html#drivers) function call ?

Gokulnathvc
17th June 2011, 14:21
It gives QSQLLITE,QODBC3, QODBC

cincirin
17th June 2011, 14:32
That means you do not have MYSQL driver plug-in. See this thread (http://www.qtcentre.org/threads/41967-Connection-to-MySQL?p=192165&highlight=#post192165) ... or search on QtCentre other threads related to this problem ...

Gokulnathvc
17th June 2011, 14:55
Connection Succeeds, But inserting fails. Am using the following code:

QFile file("D:\\image1.jpeg");
file.open(QIODevice::ReadOnly);
file.seek(0);
QByteArray buf;
buf=file.read(250000);

QSqlQuery query;
query.prepare("INSERT INTO log VALUES(grab_date='2011-04-26 15:55:09',ip_address='172.16.0.51',image=:val);");
query.bindValue ( ":val", buf);
query.exec();
Here image is the BLOB field in the database.

cincirin
17th June 2011, 15:21
If you write prepare statement as: INSERT INTO log(grab_date, ip_address, image) VALUES ('2011-04-26 15:55:09','172.16.0.51',:val) did it work ?

Gokulnathvc
17th June 2011, 15:26
I have tried with both the methods, still fails

cincirin
17th June 2011, 15:41
What is the return of last error (http://doc.qt.nokia.com/latest/qsqlquery.html#lastError) ?

ChrisW67
17th June 2011, 22:36
Connection Succeeds, But inserting fails.
Did you manage to download MySQL, build the Qt MySQL plugin, and make it work in the twenty minutes between posts 4 and 5?

You say this fails:

Am using the following code:

QFile file("D:\\image1.jpeg");
file.open(QIODevice::ReadOnly);
file.seek(0);
QByteArray buf;
buf=file.read(250000);

QSqlQuery query;
query.prepare("INSERT INTO log VALUES(grab_date='2011-04-26 15:55:09',ip_address='172.16.0.51',image=:val);");
query.bindValue ( ":val", buf);
query.exec();
Here image is the BLOB field in the database.

What about it fails?
Does a row get created without data in the blob column, is the blob data incomplete, or does no row get created?
What does QSqlQuery::lastError() tell you after each line? Cincirin identifies the really obvious invalid SQL problem but you say it still doesn't work.

Taking a step back: are you sure the file was opened successfully? You don't check. Are you sure the file had data to read and that it ended up in the QByteArray? Are you sure that 250000 bytes is large enough?

Unless you get into the habit of checking error return values, warning and messages you will always be thrashing about guessing.