-
Notifications
You must be signed in to change notification settings - Fork 3
/
student_database.cpp
60 lines (51 loc) · 1.51 KB
/
student_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
#include "student_database.h"
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include "sqlite_orm/sqlite_orm.h"
auto OpenDB(std::string className)
{
using namespace sqlite_orm;
auto Db = make_storage(className + ".db",
make_table("students",
make_column("id", &Student::id, primary_key().autoincrement()),
make_column("name", &Student::name),
make_column("sex",&Student::sex)));
Db.sync_schema();
return Db;
}
std::vector<Student> GetAllStudents(std::string className)
{
auto DB = OpenDB(className);
return DB.get_all<Student>();
}
void AddStudent(std::string className, std::string name, std::string sex)
{
auto DB = OpenDB(className);
Student i;
i.name = name;
i.sex = sex;
DB.insert(i);
}
void DeleteStudent(std::string className, std::string name)
{
using namespace sqlite_orm;
auto DB = OpenDB(className);
DB.remove_all<Student>(where(c(&Student::name) == name));
}
std::vector<Student> GetRandomStudents(std::string className, size_t count) {
auto db = OpenDB(className);
std::vector<Student> students = db.get_all<Student>();
if (students.size() < count) {
return students;
}
std::srand(static_cast<unsigned int>(std::time(nullptr)));
std::random_shuffle(students.begin(), students.end());
std::vector<Student> randomStudents;
for (size_t i = 0; i < count; ++i) {
randomStudents.push_back(students[i]);
}
return randomStudents;
}