· 4 years ago · Mar 29, 2021, 08:58 PM
1#include <Windows.h>
2#include <string>
3#include <iostream>
4#include <exception>
5#include <sstream>
6#include "sqlite3.h"
7#include <io.h>
8
9using std::string;
10using std::stringstream;
11
12void open_db(const char* name, sqlite3** db) {
13 int res = sqlite3_open(name, db);
14 if (res != SQLITE_OK) {
15 *db = nullptr;
16 throw std::runtime_error("failed to open DB");
17 }
18}
19
20void my_exec(sqlite3* db, const char* sqlStatement) {
21 std::cout << "executing: " << sqlStatement << std::endl;
22 char* errMessage = nullptr;
23 int res = sqlite3_exec(db, sqlStatement, nullptr, nullptr, &errMessage);
24 if (res != SQLITE_OK) {
25 throw std::runtime_error(errMessage);
26 }
27}
28
29void init_db(sqlite3** db) {
30 //create the person table
31 stringstream statement;
32 statement << "CREATE TABLE IF NOT EXISTS PERSONS (" <<
33 "ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," <<
34 "LAST_NAME TEXT NOT NULL," <<
35 "FIRST_NAME TEXT NOT NULL," <<
36 "EMAIL TEXT NOT NULL);";
37 my_exec(*db, statement.str().c_str());
38 statement.str(string());
39 //create the phone prefix table
40 statement << "CREATE TABLE IF NOT EXISTS PhonePrefixes (" <<
41 "PhonePrefixID INTEGER PRIMARY KEY NOT NULL," <<
42 "Prefix INTEGER NOT NULL);";
43 my_exec(*db, statement.str().c_str());
44 statement.str(string());
45 //create phone table
46 statement << "CREATE TABLE IF NOT EXISTS Phones (" <<
47 "PhoneID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," <<
48 "FOREIGN KEY(PhonePrefixID) REFERENCES PhonePrefixes(PhonePrefixID)," <<
49 "PhoneNumber INTEGER NOT NULL," <<
50 "FOREIGN KEY(PersonID) REFERENCES PERSONS(PersonID));";
51 my_exec(*db, statement.str().c_str());
52}
53
54int main() {
55 sqlite3* db;
56 string dbFileName = "PhoneBook.sqlite";
57
58 int doesFileExist = _access(dbFileName.c_str(), 0);
59 open_db(dbFileName.c_str(), &db);
60
61 if (doesFileExist == 0) {
62 try {
63 init_db(&db);
64 }
65 catch (std::runtime_error& e) {
66 std::cout << e.what() << std::endl;
67 }
68 }
69 sqlite3_close(db);
70 db = nullptr;
71
72 return 0;
73}