SQLite C/C++- CREATE Table in SQLite Database using C/C++




SQLite
SQLite
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

#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

$ 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

$ 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

$ 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>


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





1 Comment

Leave a Reply

Your email address will not be published.


*