jeudi 17 décembre 2015

Qt Changing What SQLite Database that QSqlDatabase Uses

Background
Qt5.3.2 VS2010
I have a singleton class that wraps the sqlite database that my application uses. The class has a private QSqlDatabase object that points to a sqlite database file -- "database.db". In older versions of the application, auto_vacuum pragma was not set on the database.db. Since this pragma can only be applied to a newly created database, we have to create a new database, set the pragma at that time, copy in the data from the old, and finally delete the old database.db and rename the newly created one to database.db (the name is important for other reasons).

Anyway, here is the code: Note: _db is the private reference to "database.db" and has already been opened. Also, _sql is a QSqlQuery query that already points to _db.

    QSqlDatabase newDB = QSqlDatabase::addDatabase("QSQLITE");
    newDB.setDatabaseName("newDatabase.db");
    newDB.open();
    QSqlQuery newQ(newDB);

    newQ.clear();
    newQ.exec("PRAGMA foreign_keys = ON");

    newQ.clear();
    newQ.exec("PRAGMA auto_vacuum=1");

    newQ.clear();
    newQ.prepare(createTablesText); //createTablesText is a string of all the create tables statements

    newQ.exec();
    newQ.clear();

    //copy the data from _db(database.db) to newDB(newDatabase.db)
    copyData(_sql, newQ);

    //at this point all the data should be in both databases and the database.db and newDatabase.db should be identical except for the auto_vacuum pragma
    _db.close();
    newDB.close();

after those last two lines there are where I am uncertain. I want to delete the database.db file and rename the newDatabase.db to database.db and then assign _db to use it. How would that be handled? Like this?

QFile database("database.db");
QFile newDatabase("newDatabase.db");
database.remove();
newDatabase.rename("database.db");

//then what? or does this need moved to above the rename?
QSqlDatabase::removeDatabase("database.db");
_db = QSqlDatabase::addDatabase("QSQLITE","database.db");
_db.open();
_sql = QSqlQuery(_db);

Aucun commentaire:

Enregistrer un commentaire