-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloan.cpp
More file actions
62 lines (50 loc) · 2.06 KB
/
loan.cpp
File metadata and controls
62 lines (50 loc) · 2.06 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
56
57
58
59
60
61
62
#include "loan.h"
bool operator==(const Loan& loan, const Loan& other) {
return loan.id == other.id &&
loan.user_id == other.user_id &&
loan.book_id == other.book_id &&
loan.start == other.start &&
loan.end == other.end;
}
int addLoan(sqlite3*& DB, int user_id, int book_id, QDate q_start, QDate q_end) {
sqlite3_stmt* stmt;
const char* sql = "INSERT INTO LOANS (USER_ID, BOOK_ID, START, END) VALUES (?, ?, ?, ?);";
int exit = 0;
QString start = QDateToString(q_start);
QString end = QDateToString(q_end);
exit = sqlite3_prepare_v2(DB, sql, -1, &stmt, 0);
if (exit != SQLITE_OK) {
qCritical() << "Error preparing SQL statement: " << sqlite3_errmsg(DB) << "\n";
return -1;
}
sqlite3_bind_int(stmt, 1, user_id);
sqlite3_bind_int(stmt, 2, book_id);
sqlite3_bind_text(stmt, 3, start.toUtf8().constData(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 4, end.toUtf8().constData(), -1, SQLITE_TRANSIENT);
exit = sqlite3_step(stmt);
if (exit != SQLITE_DONE) {
qCritical() << "Error executing SQL statement: " << sqlite3_errmsg(DB) << "\n";
}
else {
qDebug("Loan inserted successfully!");
}
sqlite3_finalize(stmt);
return static_cast<int>(sqlite3_last_insert_rowid(DB));
}
std::vector<Loan> getLoans(sqlite3*& DB) {
std::vector<Loan> loans;
sqlite3_stmt* stmt;
const char* sql = "SELECT ID, USER_ID, BOOK_ID, START, END FROM LOANS;";
int exit = sqlite3_prepare_v2(DB, sql, -1, &stmt, 0);
while (sqlite3_step(stmt) == SQLITE_ROW) {
int id = sqlite3_column_int(stmt, 0);
int user_id = sqlite3_column_int(stmt, 1);
int book_id = sqlite3_column_int(stmt, 2);
const char* start = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3));
const char* end = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4));
Loan loan = Loan(id, user_id, book_id, stringToQDate(start), stringToQDate(end));
loans.push_back(loan);
}
sqlite3_finalize(stmt);
return loans;
}