-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseManager.cpp
More file actions
55 lines (46 loc) · 1.3 KB
/
DatabaseManager.cpp
File metadata and controls
55 lines (46 loc) · 1.3 KB
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
#include "DatabaseManager.h"
DatabaseManager::DatabaseManager(QObject *parent)
: QObject{parent}
{
}
DatabaseManager::~DatabaseManager()
{
if (m_db.isOpen()) {
m_db.close();
}
}
bool DatabaseManager::connectToDatabase()
{
// NOTE: Update these credentials to match your local PostgreSQL setup
m_db = QSqlDatabase::addDatabase("QPSQL");
m_db.setHostName("localhost");
m_db.setDatabaseName("mwanatech_db");
m_db.setUserName("gallink");
m_db.setPassword("LS83^#NdhTSBs%^SB944dhadk52");
if (!m_db.open()) {
qCritical() << "Error: connection with database failed";
qCritical() << m_db.lastError().text();
qCritical() << "Available drivers:" << QSqlDatabase::drivers();
return false;
}
qDebug() << "Database: connection ok";
// Ensure table exists
QSqlQuery query;
bool success = query.exec(
"CREATE TABLE IF NOT EXISTS books ("
"id SERIAL PRIMARY KEY, "
"title TEXT NOT NULL, "
"author TEXT NOT NULL, "
"status TEXT NOT NULL, "
"contact_name TEXT, "
"contact_number TEXT)"
);
if (!success) {
qCritical() << "Error creating table:" << query.lastError().text();
}
return true;
}
QSqlDatabase DatabaseManager::db() const
{
return m_db;
}