#include "db.h" #include #include sqlite3 *initDB() { sqlite3 *db; int rc = sqlite3_open("jokes.db", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database %s\n", sqlite3_errmsg(db)); return NULL; } return db; } char *GetJoke(sqlite3 *db) { sqlite3_stmt *stmt; char *sql ="select joke from Jokes order by random() limit 1;"; int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); if (rc != SQLITE_OK) { fprintf(stderr, "Could not read DB: %s\n", sqlite3_errmsg(db)); return NULL; } if (sqlite3_step(stmt) == SQLITE_ROW) { char *data = (char *)sqlite3_column_text(stmt, 0); char *joke = strdup(data); sqlite3_finalize(stmt); sqlite3_close(db); return joke; } return NULL; } bool DeleteJoke(sqlite3 *db, int id) { char sql[64]; char *errMsg; sprintf(sql, "delete from Jokes where id=%d;", id); int rc = sqlite3_exec(db, sql, 0, 0, &errMsg); if (rc != SQLITE_OK) { fprintf(stderr, "Could not delete: %s\n", errMsg); sqlite3_free(errMsg); return false; } return true; } bool NewJoke(sqlite3 *db, char *data) { return true; } int JokeCount(sqlite3 *db) { int count = 0; sqlite3_stmt *stmt; const char *sql = "select count(*) from Jokes;"; int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); if (rc != SQLITE_OK) { fprintf(stderr, "Could not get count from db: %s\n", sqlite3_errmsg(db)); return -1; } while ((rc = sqlite3_step(stmt)) != SQLITE_DONE) { count = sqlite3_column_int(stmt, 0); } return count; }