Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2022
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include "sqlite3.h"
  3. #include "stdbool.h"
  4. #include "string.h"
  5.  
  6. bool table_exists(sqlite3* db, const char* table_name){
  7.     sqlite3_stmt* statement;
  8.     int rc;
  9.  
  10.     const char* sql_table_list = "SELECT name FROM sqlite_master WHERE type='table'";
  11.  
  12.     rc = sqlite3_prepare_v2(db, sql_table_list, (int)strlen(sql_table_list), &statement, NULL);
  13.     if(rc == SQLITE_OK) {
  14.         // Loop through all the tables
  15.         while(sqlite3_step(statement) == SQLITE_ROW) {
  16.             if(!strcmp((const char*) sqlite3_column_text(statement, 0), table_name))
  17.                 return true;
  18.         }
  19.     }
  20.  
  21.     return false;
  22. }
  23.  
  24. bool create_user_table(sqlite3* db){
  25.     sqlite3_stmt* statement;
  26.     int rc;
  27.  
  28.     // SQL query to create the 'user' table
  29.     const char* sql_create_user_table = "CREATE TABLE users ("
  30.                                         "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,"
  31.                                         "first_name TEXT NOT NULL,"
  32.                                         "last_name TEXT NOT NULL,"
  33.                                         "grade_level INTEGER NOT NULL,"
  34.                                         "group_identifier TEXT NOT NULL,"
  35.                                         "gpa REAL NOT NULL);";
  36.  
  37.     // Execute the previous query to create the 'user' table
  38.     rc = sqlite3_prepare_v2(db, sql_create_user_table, (int)strlen(sql_create_user_table), &statement, NULL);
  39.     if(rc != SQLITE_OK) {
  40.         fprintf(stderr, "Can't initialize the database: %s\n", sqlite3_errmsg(db));
  41.         return false;
  42.     }
  43.  
  44.     sqlite3_step(statement);
  45.     sqlite3_finalize(statement);
  46.  
  47.  
  48.     return true;
  49. }
  50.  
  51. int main(){
  52.  
  53.     sqlite3* db;
  54.     int rc = sqlite3_open("users.db", &db);
  55.  
  56.     if(rc != SQLITE_OK) {
  57.         fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
  58.         sqlite3_close(db);
  59.         return 1;
  60.     }
  61.  
  62.     if(!table_exists(db, "users")) {
  63.         // Create 'user' table
  64.         if(!create_user_table(db)) {
  65.             sqlite3_close(db);
  66.             return 1;
  67.         }
  68.     }
  69.  
  70.  
  71.     sqlite3_close(db);
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement