QT database; create table with helper class






The complete project can be downloaded from here. Instead of writing very messy code in mainwidow.h, the helper class is to minimize coding and to improve clarity. 

Function: 
(1) To open database at start up
(2) To create or delete a table from database



At mainwindow.h
(1) 'database' file is passed to setDataBasePath. This will return bool operator and check whether the database can be opened or not. 'database.db' is created at application folder.

(2) When "Create Table" is clicked, status of 'Creation of Table' changed to 'Table Created'. If table already exists at database, the status changes to 'Failed to create table'.

(3) Similarly, when "Drop Table" is clicked, status of 'Creation of Table' changed to 'Table Dropped'. If table DOES NOT exist at database, the status changes to 'Failed to drop the table'.

(4) Take note that, same table name is created and deleted during this program.


#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    if (dBH.setDataBasePath("database")) {
        ui->label_status->setText("Connected");
    } else {
        ui->label_status->setText("Failed");
    }
}
MainWindow::~MainWindow() {
    delete ui;
}
void MainWindow::on_createTable_clicked() {
    bool isTableCreated = dBH.createTable();
    if (isTableCreated) {
        ui->status_tableCreated->setText("Table Created");
    }
    else {
        ui->status_tableCreated->setText("Failed to create table");
    }
}
void MainWindow::on_dropTable_clicked() {
    bool isTableDropped = dBH.dropTable();
    if (isTableDropped) {
        ui->status_tableCreated->setText("Table Dropped");
    }
    else {
        ui->status_tableCreated->setText("Failed to drop the table");
    }
}













At databasehelper.h, all of the necessary steps and traps are properly commented. Please go through.


#include "databasehelper.h"
#include <QDebug>

DatabaseHelper::DatabaseHelper() //default constructor
{
    //needed it in constructor otherwise, database can't be opened from other function call; werid
    myDataBase = QSqlDatabase::addDatabase("QSQLITE"); //QSLITE must be exact
}

bool DatabaseHelper::setDataBasePath(QString filename) {

//another file *.db will be created if the file is not presented on the system
    QString dbPath = QCoreApplication::applicationDirPath() + "/" + filename
            + ".db";
    myDataBase.setDatabaseName(dbPath);
    if (myDataBase.open()) {

        qDebug() << "databased is opened sucessfully ";
        return true;
    } else {
        qDebug() << "failed to open databased";
        return false;
    }
}

bool DatabaseHelper::createTable() {
    if (myDataBase.isOpen()) {

        QSqlQuery query(myDataBase);
        //you can use "create table if not exists" but it will be always
        //successful to execute this following command

        //Name of table cannot be variable//
        //so have to hard code it//
        //it is just sqlite way//
        bool ret = query.exec("create table studentTable"
                "(id integer primary key, "
                "firstname varchar(20), "
                "lastname varchar(30), "
                "age integer)");

        if (ret) {
            qDebug() << "table created";
            return true;
        } else {
            qDebug() << "faied to crate table";
            return false;
        }
    } else {
        return false;
    }
}

bool DatabaseHelper::dropTable() {

    if (myDataBase.isOpen()) {
        QSqlQuery query(myDataBase);
        bool ret = query.exec("drop table studentTable");

        if (ret) {
            qDebug() << "table dropped";
            return true;
        } else {
            qDebug() << "faied to drop the table";
            return false;
        }
    } else {
        return false; //return false if failed to open database
    }
}

DatabaseHelper::~DatabaseHelper() //default deconstructor
{

}

No comments:

Post a Comment