Hi everyone,
I'd like to create a simple class to run my queries in my program.
The sctructure is:
---------------------------------------------
::: libdb.h
---------------------------------------------
#ifndef LIBDB_H
#define LIBDB_H
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
#include <QDebug>
class DataBase
{
public:
DataBase();
virtual ~DataBase();
};
#endif // LIBDB_H
#ifndef LIBDB_H
#define LIBDB_H
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
#include <QDebug>
class DataBase
{
public:
DataBase();
virtual ~DataBase();
QSqlQuery setQuery(QString);
};
#endif // LIBDB_H
To copy to clipboard, switch view to plain text mode
---------------------------------------------
::: libdb.cpp
---------------------------------------------
#include "libdb.h"
DataBase::DataBase()
{
}
DataBase::~DataBase()
{
}
{
db.setHostName("10.0.2.2");
db.setDatabaseName("testdb");
db.setUserName("root");
db.setPassword("password");
if (!db.open()) {
qDebug() << "database wasn't opened";
return NULL;
} else {
sqlquery.prepare(sql_statement);
sqlquery.exec();
db.commit();
db.close();
return sqlquery;
}
}
#include "libdb.h"
DataBase::DataBase()
{
}
DataBase::~DataBase()
{
}
QSqlQuery setQuery(QString sql_statement)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("10.0.2.2");
db.setDatabaseName("testdb");
db.setUserName("root");
db.setPassword("password");
if (!db.open()) {
qDebug() << "database wasn't opened";
return NULL;
} else {
QSqlQuery sqlquery(sql_statement, db);
sqlquery.prepare(sql_statement);
sqlquery.exec();
db.commit();
db.close();
return sqlquery;
}
}
To copy to clipboard, switch view to plain text mode
---------------------------------------------
::: mainwindow.cpp
---------------------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "libdb.h"
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
DataBase mDB = DataBase();
query = mDB.setQuery("SELECT * FROM alarm");
while(query.next()) {
QString alarm
= query.
value(0).
toString();
qDebug() << "Alarms: " << alarm;
}
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "libdb.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
DataBase mDB = DataBase();
QSqlQuery query;
query = mDB.setQuery("SELECT * FROM alarm");
while(query.next()) {
QString alarm = query.value(0).toString();
qDebug() << "Alarms: " << alarm;
}
}
To copy to clipboard, switch view to plain text mode
But, I've gotting the error:
undefined reference to `Database::setQuery(QString)' mainwindow.cpp13
mainwindow.cpp13 = 'query = mDB.setQuery("SELECT * FROM alarm");'
What I'm doing wrong?
Thanks.
Bookmarks