add some random code playing with sqlite3 C api
[matches/MCTX3420.git] / testing / sqlite-approach / testapp / test.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sqlite3.h>
5
6 static void updateSensor(sqlite3* db, int id, int value);
7
8 int main(int argc, char *argv[]) {
9         if (argc != 2) {
10                 printf ("Usage: %s db_location\n", argv[0]);
11                 return 1;
12         }
13
14         sqlite3* db;
15         int ret;
16
17         if (ret = sqlite3_open(argv[1], &db) != SQLITE_OK) {
18                 printf("Error opening database: %s\n",
19                         sqlite3_errstr(ret));
20                 return 1;
21         }
22
23         sqlite3_stmt *statement;
24         char *query = "insert into sensors values(3,4)";
25         if (ret = sqlite3_prepare(db, query, (int)strlen(query) + 1, &statement, NULL) != SQLITE_OK) {
26                 printf("Error in query: %s\n",
27                         sqlite3_errstr(ret));
28         }
29
30         sqlite3_step(statement);
31         sqlite3_finalize(statement);
32
33         updateSensor(db, 44, 2332);
34         sqlite3_close(db);
35         return 0;
36 }
37
38 static void updateSensor(sqlite3* db, int id, int value) {
39         char query[BUFSIZ];
40         snprintf(query, BUFSIZ, "update sensors set value=%d where id=%d", value, id);
41
42         //Needs error checking
43         int ret;
44         if (ret = sqlite3_exec(db, query, NULL, NULL, NULL) != SQLITE_OK) {
45                 printf("Error: %s\n", sqlite3_errstr(ret));
46         }
47         if (!sqlite3_changes(db)) {
48                 printf("Record doesn't exist; creating!\n");
49                 snprintf(query, BUFSIZ, "insert into sensors values(%d, %d)", id, value);
50                 sqlite3_exec(db, query, NULL, NULL, NULL);
51         }
52 }

UCC git Repository :: git.ucc.asn.au