-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.cpp
120 lines (102 loc) · 2.59 KB
/
database.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include "database.h"
Database::Database(QObject *parent) : QObject(parent)
{
}
Database::~Database()
{
}
void Database::connectToDatabase()
{
if(!QFile("/home/aliakbar/" Database_NAME).exists()) {
this->restorDatabase();
} else {
this->openDatabase();
}
}
bool Database::openDatabase()
{
db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName(Database_HOSTNAME);
db.setDatabaseName("/home/aliakbar/" Database_NAME);
if(db.open()) {
return true;
} else {
return false;
}
}
bool Database::restorDatabase()
{
if(this->openDatabase()) {
return this->createTable() ? true : false;
} else {
qDebug() << "Failed to restore the database";
return false;
}
return false;
}
bool Database::closeDatabase()
{
db.close();
return true;
}
bool Database::createTable()
{
QSqlQuery query;
if(!query.exec("CREATE TABLE " TABLE " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
"firstname VARCHAR(255) NOT NULL, "
"lastname VARCHAR(255) NOT NULL, "
"mobile VARCHAR(255) NOT NULL"
");"
)) {
qDebug() << "Database: error of create " << TABLE;
qDebug() << query.lastError().text();
return false;
} else {
return true;
}
return false;
}
bool Database::insertIntoTable(const QVariantList &data)
{
QSqlQuery query;
query.prepare("INSERT INTO " TABLE " (firstname, "
"lastname, "
"mobile )"
"VALUES (:firstname, :lastname, :mobile)");
query.bindValue(":firstname", data[0].toString());
query.bindValue(":lastname", data[1].toString());
query.bindValue(":mobile", data[2].toString());
if(!query.exec()) {
qDebug() << "error insert into " TABLE;
qDebug() << query.lastError().text();
return false;
} else {
return true;
}
return false;
}
bool Database::insertIntoTable(const QString &fname, const QString &sname, const QString &nik)
{
QVariantList data;
data.append(fname);
data.append(sname);
data.append(nik);
if(insertIntoTable(data))
return true;
else
return false;
}
bool Database::removeRecord(const int id)
{
QSqlQuery query;
query.prepare("DELETE FROM " TABLE " WHERE id= :ID ;");
query.bindValue(":ID", id);
if(!query.exec()) {
qDebug() << "error delete row " << TABLE;
qDebug() << query.lastError().text();
return false;
} else {
return true;
}
return false;
}