There are many similar questions on here already but unfortunately, none has solved my problem so far.
I am stuck connecting Qt to a simple sqlite database. The connection can be established, but queries fail with No query Unable to fetch row
and db.tables()
returns me no tables.
My code is the following:
void DBManager::connOpen()
{
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(m_db_path);
m_db.open();
if (!m_db.open())
{
qDebug("Error: Connection to database failed.");
}
else
{
qDebug("Connection to database established.");
QSqlQuery query(m_db);
query.prepare("SELECT * FROM data1");
if (!query.exec())
{
std::cout << query.lastError().text().toStdString() << std::endl;
std::cout << query.executedQuery().toStdString() << std::endl;
}
while (query.next())
{
std::cout << query.value("id").toString().toStdString() << ". " << query.value("one").toString().toStdString() << std::endl;
}
QSqlDriver *driver = m_db.driver();
QStringList tables = m_db.tables();
std::cout << "tables found: " << tables.count() << std::endl;
for(QString table: tables)
{
QSqlRecord record = driver->record(table);
std::cout << "name: " << table.toStdString() << std::endl;
std::cout << "count: " << record.count() << std::endl;
std::cout << record.fieldName(0).toStdString() << std::endl;
}
}
}
This leads to console output like this:
Connection to database established.
No query Unable to fetch row
SELECT * FROM data1
tables found: 0
My database should have one table (data1). Executing the query by hand returns this:
Any help is appreciated, thank you.
It came down to a very stupid mistake.
I was using a sqlite2 database that I created using sqlite mydb
while QSQLITE
is the driver for sqlite3 (using sqlite3 mydb
).