PDA

View Full Version : QSqlite issues



duave
3rd April 2011, 22:53
Hey guys,

I'm having this trouble in QT - I was wondering if somebody could explain to me what's going on.

I'm using this code:

timingDatabase = QSqlDatabase::addDatabase("QSQLITE", "timing");
timingDatabase.setDatabaseName("../config.db");
if (!timingDatabase.open())
{
qDebug() << timingDatabase.lastError();
}

if (!timingDatabase.tables().contains("timing"))
ConstructTimeSettingsTable();

and also

void TimingSettings::ConstructTimeSettingsTable()
{
qDebug() << timingDatabase.tables();
QSqlQuery timeQuery;
timeQuery.exec("CREATE TABLE timing ("
"line1 STRING, "
"line2 STRING, "
"line3 STRING"
");");
qDebug() << timeQuery.lastError();
qDebug() << "Construct function entered.";
}


If I am correct - my program should run the Construct...() if the timing table does not exist (i.e. the first time the program is ran).. However, that is not the case - this is the output I am getting from my qDebug everytime I run the program:

()
QSqlError(1, "Unable to execute statement", "table timing already exists")
Construct function entered.

(1) the first "()" is what timingDatabase.tables() - as in there are no tables in the database, am I right?
(2) if the timingDatabase.tables() is NULL, why is the timingQuery.exec unable to run because the table already exists..?
(3) I've also written debugging code to try to write to and from the database - but the code does not do anything.

If you guys could point me in the right direction of what is wrong with my code, it would be much appreciated.

ChrisW67
3rd April 2011, 23:19
First listing line 1 creates a connection named "timing". Second listing line 4 creates a query that is using the default database, not the named database connection "timing". In your program there must be a default database, and that is where the timing table is being created.

Change line 4 to read:


QSqlQuery timeQuery(timeDatabase);

b1
3rd April 2011, 23:32
duave,

The only thing that I see strange with your code is the following line but then I am no expert either.


timingDatabase = QSqlDatabase::addDatabase("QSQLITE", "timing");

I am not sure about the "timing" being in the definition. To do what you want I did it this way:


timeQuery.exec( "CREATE TABLE IF NOT EXISTS timing ("
"`line1` varchar(10) default NULL,"
"`line2` varchar(10) default NULL,"
"`line3` varchar(10) default NULL)" );
if (!timeQuery.isActive() )
{
QMessageBox::critical(this, "Error", "Table Creation Failed! \n"
"\n"+dbqry.lastError().text()+"n"+timingDatabase.driverName() );
}

I have an application that requires three tables and I use this method to check each table is there. If not, its created. Also, the the database is created if not there either.

Hope this helps.

B1.