61 lines
1.2 KiB
C
61 lines
1.2 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <sqlite3.h>
|
||
|
|
||
|
#include "db.h"
|
||
|
|
||
|
extern sqlite3 *db;
|
||
|
|
||
|
static char *get_db_path(void)
|
||
|
{
|
||
|
char *path;
|
||
|
|
||
|
path = getenv(IOC_DB);
|
||
|
return !path ? DB_PATH : path;
|
||
|
}
|
||
|
|
||
|
void create_table(sqlite3 *db)
|
||
|
{
|
||
|
char *err_msg;
|
||
|
|
||
|
if (sqlite3_exec(db, QUERY_CREATE_TABLE, 0, 0, &err_msg) != SQLITE_OK) {
|
||
|
fprintf(stderr, "Failed to create table: %s\n", err_msg);
|
||
|
sqlite3_free(err_msg);
|
||
|
exit(1);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void clean_db(sqlite3 *db)
|
||
|
{
|
||
|
sqlite3_close(db);
|
||
|
}
|
||
|
|
||
|
void init_db(sqlite3 **db)
|
||
|
{
|
||
|
if (sqlite3_open(get_db_path(), db) != SQLITE_OK) {
|
||
|
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(*db));
|
||
|
exit(1);
|
||
|
}
|
||
|
create_table(*db);
|
||
|
}
|
||
|
|
||
|
void insert_data(char *device_id, char *sensor_type, int data)
|
||
|
{
|
||
|
sqlite3_stmt *res;
|
||
|
|
||
|
if (sqlite3_prepare_v2(db, QUERY_INSERT_DATA, -1, &res, 0) != SQLITE_OK) {
|
||
|
fprintf(stderr, "Failed to execute statement: %s\n", sqlite3_errmsg(db));
|
||
|
exit(1);
|
||
|
}
|
||
|
|
||
|
sqlite3_bind_text(res, 1, device_id, -1, NULL);
|
||
|
sqlite3_bind_text(res, 2, sensor_type, -1, NULL);
|
||
|
sqlite3_bind_int(res, 3, data);
|
||
|
|
||
|
if (sqlite3_step(res) != SQLITE_DONE) {
|
||
|
fprintf(stderr, "Failed to execute sqlite3_step\n");
|
||
|
sqlite3_finalize(res);
|
||
|
exit(1);
|
||
|
}
|
||
|
}
|