SQLite C/C++ – CREATE Table in SQLite Database using C/C++
SQLite C/C++- CREATE Table in SQLite Database using C/C++
Make a C Program file and Name it as main.c and write the following C/C++ Code
Basic Syntex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include <sqlite3.h> #include <stdio.h> int main(void) { sqlite3 *db; char *err_message = 0; int rc = sqlite3_open("student.db", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Can not open the database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } else { fprintf(stdout, "Database Opened successfully\n"); } char *sql_query = "DROP TABLE IF EXISTS STUDENTS;" "CREATE TABLE STUDENTS(Id INT PRIMARY KEY NOT NULL, Name TEXT, Surname TEXT);"; rc = sqlite3_exec(db, sql_query, 0, 0, &err_message); if (rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", err_message); sqlite3_free(err_message); sqlite3_close(db); return 1; } else { fprintf(stdout, "Table STUDENTS created successfully\n"); } sqlite3_close(db); return 0; } |
compile your code with following command
1 2 3 4 |
$ gcc main.c -l sqlite3 $ ./a.out Database Opened successfully Table STUDENTS created successfully |
You will also notice a SQLite database named student.db in the same folder containing you main.c file
1 2 |
$ ls a.out main.c student.db |
In student.db the STUDENTS table is created after running the code above. You can verify the schema of the student table in SQLite database by running following commands
1 2 3 4 5 6 7 8 |
$ sqlite3 student.db SQLite version 3.11.0 2016-02-15 17:29:24 Enter ".help" for usage hints. sqlite> .tables STUDENTS sqlite> .schema CREATE TABLE STUDENTS(Id INT PRIMARY KEY NOT NULL, Name TEXT, Surname TEXT); sqlite> |