Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a table exists

Tags:

sqlite

qt

I am using this SELECT name FROM sqlite_master WHERE type = "table" AND name = 'create_organization'; to check if the table named create_organization exists and it works.However i would like to use qt to find that out.I am trying

 QSqlQuery query;
    QString tableName = "employee_datastores";
    QString sqlQuery = QString("SELECT name FROM sqlite_master WHERE type =:table AND name = %1 ").arg(tableName);
    query.prepare(sqlQuery);
    query.bindValue(":table", "table");
    query.exec();
    int fieldNo = query.record().indexOf("employee_datastore_name");
    while (query.next()) {
        QString employee_ds_name = query.value(fieldNo).toString();
        qDebug() << "Table Name" << employee_ds_name ;
    }

but it does not work.

like image 590
Gandalf Avatar asked Nov 26 '11 10:11

Gandalf


2 Answers

Does QSqlDatabase::tables() give you what you want? For example you could try:

if ( database.tables().contains( QLatin1String("employee_datastores") ) {
    ...
}
like image 65
JediLlama Avatar answered Sep 27 '22 21:09

JediLlama


You could fix it like this:

QString sqlQuery = QString("SELECT name FROM sqlite_master WHERE type =:table AND name = '%1' ").arg(tableName);
query.prepare(sqlQuery);
query.bindValue(":table", "table");
query.exec();

But why mix bind values and "dumb" string replacement?

QString sqlQuery = QString("SELECT name FROM sqlite_master WHERE type =:table AND name = :tablename ");
query.prepare(sqlQuery);
query.bindValue(":table", "table");
query.bindValue(":tablename", tableName);
query.exec();
like image 36
Mat Avatar answered Sep 27 '22 23:09

Mat