PDA

View Full Version : Basic Qt Sql Question



sidenelen
31st March 2012, 01:31
Hello,

I was trying to build a simple connection to my database that i created recently. But it seems my code doesn't work or sth else wrong. Actually I want to show the values from database file.

Here's the code :





#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QtDebug>
#include <iostream>
using namespace std;

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



QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

db.setConnectOptions();

db.setDatabaseName("deneme");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("2245009");


if(db.open())
{
cout<<"opened"<<endl;

QSqlQuery qry;
if(qry.exec("SELECT *FROM `tablo` 1"))

{
while(qry.next())
{
//qDebug() << qry.value(1).toString();
qDebug() << qry.value(1);
}
}
else
{
qDebug() << "error = " << db.lastError().text();
}
cout<<"closing"<<endl;
db.close();

}
else
{
qDebug() << "error = " << db.lastError();
}

return a.exec();
}






The output is like that :



Starting /home/onur/dbapp-build-desktop/dbapp...
opened
closing
error = " "


It shows an empty error. I didn't understand anything because of being a newbie. Any advices?

Thanks in Advance!

wysota
31st March 2012, 01:58
Do you have a SQLite database file called "deneme" in your current working directory?

sidenelen
31st March 2012, 03:13
thank you for your reply. i didn't have. now changed, but still the same problem.

norobro
31st March 2012, 03:52
Try "qry.lastError().text()" @ line 39 in lieu of "db.lastError().text()"

sidenelen
31st March 2012, 04:24
now the error changes like:



error = "near "1": syntax error Unable to execute statement"

Lykurg
31st March 2012, 07:07
What wysota was trying to say to you is: You are using the wrong database driver for MySql. This is most probably also the reason why the query throws an error. Not all database systems understand the same SQL commands.

wysota
31st March 2012, 08:58
now the error changes like:

And if you correct the syntax? Does it work then?

Lesiok
31st March 2012, 13:01
Yours SQL query is bad
SELECT * FROM `tablo` 1
It should be
SELECT * FROM `tablo`
or

SELECT * FROM `tablo` WHERE 1
Of course, the latter figure does not make sense.

sidenelen
31st March 2012, 13:47
@Lesiok
Yeah, I corrected the code as you said and it works! Thank you all guys