Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include "sqlite3.h"
- #include "stdbool.h"
- #include "string.h"
- bool table_exists(sqlite3* db, const char* table_name){
- sqlite3_stmt* statement;
- int rc;
- const char* sql_table_list = "SELECT name FROM sqlite_master WHERE type='table'";
- rc = sqlite3_prepare_v2(db, sql_table_list, (int)strlen(sql_table_list), &statement, NULL);
- if(rc == SQLITE_OK) {
- // Loop through all the tables
- while(sqlite3_step(statement) == SQLITE_ROW) {
- if(!strcmp((const char*) sqlite3_column_text(statement, 0), table_name))
- return true;
- }
- }
- return false;
- }
- bool create_user_table(sqlite3* db){
- sqlite3_stmt* statement;
- int rc;
- // SQL query to create the 'user' table
- const char* sql_create_user_table = "CREATE TABLE users ("
- "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,"
- "first_name TEXT NOT NULL,"
- "last_name TEXT NOT NULL,"
- "grade_level INTEGER NOT NULL,"
- "group_identifier TEXT NOT NULL,"
- "gpa REAL NOT NULL);";
- // Execute the previous query to create the 'user' table
- rc = sqlite3_prepare_v2(db, sql_create_user_table, (int)strlen(sql_create_user_table), &statement, NULL);
- if(rc != SQLITE_OK) {
- fprintf(stderr, "Can't initialize the database: %s\n", sqlite3_errmsg(db));
- return false;
- }
- sqlite3_step(statement);
- sqlite3_finalize(statement);
- return true;
- }
- int main(){
- sqlite3* db;
- int rc = sqlite3_open("users.db", &db);
- if(rc != SQLITE_OK) {
- fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
- sqlite3_close(db);
- return 1;
- }
- if(!table_exists(db, "users")) {
- // Create 'user' table
- if(!create_user_table(db)) {
- sqlite3_close(db);
- return 1;
- }
- }
- sqlite3_close(db);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement