PDA

View Full Version : Execute sql queries on multiple databases



Cyrebo
18th April 2013, 22:31
I want execute queries on my main and backup database, how do i do it? I currently have two connections running until I go to execute a query, I get the error database not open. I'm open to suggestions outside of this program to maintaining an efficient contemporaneous backup system.

My code:


{
ui->setupUi(this);
//Setup DB connection
db2 = QSqlDatabase::addDatabase("QSQLITE", "main");
db2.setDatabaseName(Path_to_DB);
QFileInfo checkFile(Path_to_DB);

if(checkFile.isWritable())
{
if(db2.open())
{
qDebug() << "Connected to database file";
}
}else{
qDebug() << "Database file not found";
}

dbb = QSqlDatabase::addDatabase("QSQLITE", "backup");
dbb.setDatabaseName(Path_to_DBBackup);
QFileInfo checkFile2(Path_to_DBBackup);

if(checkFile2.isWritable())
{
if(dbb.open())
{
qDebug() << "Connected to database backup file";
}
}else{
qDebug() << "Database file not found";
}

QString email = ui->email->text();
QString q = QString("SELECT * FROM users WHERE email = '%1'").arg(email);
QSqlQuery qry;
if(qry.exec(q))
{
if (qry.next())
{
return false;
}
}
else{qDebug() << "Query unsuccessful!";}
}


Everything works when I query just one db...

Thanks in advance.

ChrisW67
19th April 2013, 00:57
You are creating a QSqlQuery [line 34] operating on the default connection, which is neither of the two connections your code opens.

Cyrebo
19th April 2013, 19:32
Can you show me how to query multiple databases in qt?

Lesiok
20th April 2013, 08:55
Defining QSqlQuery you specify the database to which it relates, eg
QSqlQuery qry(db2);

Cyrebo
22nd April 2013, 22:32
This thread is solved now thanks.