-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase_testing_1.cpp
131 lines (121 loc) · 3.12 KB
/
database_testing_1.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
121
122
123
124
125
126
127
128
129
130
131
#include <iostream>
#include "sqlite3.h"
using namespace std;
class database
{
private:
sqlite3 *db1;
char *zErrMsg = 0;
int rc;
char const *sql;
char const *data = "\n\t callback invoked";
public:
void open_db()
{
//open database or create if does not exist
rc = sqlite3_open("/D:/KIT/Semester 4/mini project/inventory.db", &db1);
//check for errors in creation or opening
if (rc)
{
cout << "\n\tUnable to open database";
cout << "\n\tError:" << sqlite3_errmsg(db1);
}
else
{
cout << "\n\t database opened successfully";
}
}
void create()
{
//sql query to create
sql = "CREATE TABLE STOCK("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"CATEGORY TEXT NOT NULL,"
"PRICE REAL NOT NULL,"
"QTY INT NOT NULL);";
//executes sql query to create STOCK table
rc = sqlite3_exec(db1, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK)
{
cout << "\n\tunable to create table";
cout << "\n\tError:" << zErrMsg;
sqlite3_free(zErrMsg);
}
else
{
cout << "\n\t Table created successfully";
}
}
void insert()
{
//sql insert query
sql = "INSERT INTO STOCK (ID,NAME,CATEGORY,PRICE,QTY)"
"VALUES (235,'cheese','FMCG',50.00,10);";
rc = sqlite3_exec(db1, sql, callback, (void *)data, &zErrMsg);
if (rc != SQLITE_OK)
{
cout << "\n\tunable to INSERT RECORD";
cout << "\n\tError:" << zErrMsg;
sqlite3_free(zErrMsg);
}
else
{
cout << "\n\t RECORD created successfully";
}
}
void select()
{
//sql select query
sql = "SELECT * FROM STOCK";
rc = sqlite3_exec(db1, sql, callback, (void *)data, &zErrMsg);
if (rc != SQLITE_OK)
{
cout << "\n\tunable to FETCH RECORD";
cout << "\n\tError:" << zErrMsg;
sqlite3_free(zErrMsg);
}
else
{
cout << "\n\t RECORDS fetched successfully";
}
}
void dlt()
{
cout << "demo, nothing implemented";
}
void exit()
{
sqlite3_close(db1);
}
//callback function displays the records
static int callback(void *data, int col_in_row, char **fields_in_row, char **Col_names)
{
cout << (const char *)data;
for (int i = 0; i < col_in_row; i++)
{
cout << "\n\t " << Col_names[i] << ":" << fields_in_row[i];
}
cout << "\n";
return 0;
}
};
void db_test()
{
int choice;
database obj;
obj.open_db();
obj.insert();
obj.select();
cin >>choice;
cout<<choice;
/* do{
cout<<"\n\tYour choice:";
cin>>choice;
switch(choice){
case 1:
obj.create();
}
}while(choice!=5);*/
//close connection to database
}