From 2052137673eaec04d41353cf12dc3d1c95a2c18a Mon Sep 17 00:00:00 2001 From: SuperNovaa41 Date: Mon, 3 Mar 2025 12:50:43 -0500 Subject: [PATCH] some db functions --- src/db.c | 33 +++++++++++++++++++++++++++++++++ src/include/db.h | 2 ++ 2 files changed, 35 insertions(+) diff --git a/src/db.c b/src/db.c index 2456232..9e44c8e 100644 --- a/src/db.c +++ b/src/db.c @@ -1,9 +1,22 @@ #include #include #include +#include #include "include/db.h" +static void open_db(sqlite3** db) +{ + int err; + + err = sqlite3_open("books.db", db); + if (err != SQLITE_OK) { + fprintf(stderr, "Cannot open db: %s\n", sqlite3_errmsg(*db)); + sqlite3_close(*db); + exit(EXIT_FAILURE); + } +} + static int get_num_rows(sqlite3* db) { int rows = 0; @@ -22,6 +35,8 @@ void setup_db(sqlite3* db) int err; char* err_buf = 0; + open_db(&db); + err = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS books (id UNSIGNED INT PRIMARY KEY, \ title TEXT, subtitle TEXT, isbn TEXT, authors TEXT, subjects TEXT, \ @@ -34,4 +49,22 @@ void setup_db(sqlite3* db) sqlite3_close(db); exit(EXIT_FAILURE); } + + sqlite3_close(db); +} + +#define INSERT_STR "INSERT INTO books (id, title, subtitle, isbn, authors, subjects, langs, date_added, date_completed, pub_date, image_code, year_of_pub, page_len) VALUES(" + +void add_to_db(book_t* book, sqlite3* db) +{ + int id; + char* cmd; + + open_db(&db); + + id = get_num_rows(db) + 1; + + cmd = malloc(sizeof(char) * (strlen(INSERT_STR) + 1)); + snprintf(cmd, strlen(INSERT_STR), "%s", INSERT_STR); + } diff --git a/src/include/db.h b/src/include/db.h index c9d7ab3..33b3f77 100644 --- a/src/include/db.h +++ b/src/include/db.h @@ -14,4 +14,6 @@ typedef struct { void setup_db(sqlite3* db); +void add_to_db(book_t* book, sqlite3* db); + #endif