vaettchen
vaettchen

Reputation: 7659

Qt: Can't connect to SQLite DB

Doing my first steps in Qt Creator and lost already:

To a basic, otherwise unchanged starting app from the Qt wizard, I have added sql to the project file

QT       += core gui sql

and the lines below to mainwindow.cpp.

#include <QSqlDatabase>

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("/home/vaettchen/testSQL/myDB.sqlite");
bool db_ok = db.open();

According to various sources on the Qt WebSite and here on SO, I had expected that this would do it. But I get a compiler error

../testSQL/mainwindow.cpp:20:1: error: 'db' does not name a type

where line 20 is the db.setDataBaseName() line. I have tried to find out via Google what this means and what can be done about it but the comments I found were not very useful.

Using Qt Creator 2.7.0 (Qt 4.8.4) on Linux 3.5

Upvotes: 0

Views: 1895

Answers (1)

nickrak
nickrak

Reputation: 1635

It appears that the compiler is trying to interpret 'db' as a type, which leads me to believe that lines 19-21 are not in a function.

#include "mainwindow.h"    
#include "ui_mainwindow.h"
#include <QSqlDatabase>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("/home/vaettchen/testSQL/myDB.sqlite");
    bool db_ok = db.open();
}

Upvotes: 1

Related Questions