C program to create database table dynamically in SQLite

Here, we are going to write a C program to create database table dynamically in SQLite.
By Nidhi Last updated : March 10, 2024

Prerequisites

The following packages need to be installed in the ubuntu machine for Sqlite connectivity using the C program.

sudo apt install sqlite3
sudo apt install gcc
sudo apt install libsqlite3-dev

Problem Solution

In this program, we will create a database table using source code dynamically in SQLite.

Program/Source Code

The source code to create a database table dynamically is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to create a database table dynamically in SQLITE.

#include <sqlite3.h>
#include <stdio.h>

int main(void)
{
    sqlite3* db_ptr;
    char* errMesg = 0;

    int ret = 0;

    ret = sqlite3_open("MyDb.db", &db_ptr);

    if (ret != SQLITE_OK) {
        printf("Database opening error\n");
    }

    ret = sqlite3_exec(db_ptr, "create table Employee (Eid INT, EName TEXT, Salary INT)", 0, 0, &errMesg);

    if (ret != SQLITE_OK) {

        printf("Error in SQL statement: %s\n", errMesg);

        sqlite3_free(errMesg);
        sqlite3_close(db_ptr);

        return 1;
    }

    printf("Employee table created successfully\n");
    sqlite3_close(db_ptr);

    return 0;
}

Output

$ gcc create_table.c -o create_table -lsqlite3 -std=c99
$  ./create_table 
Employee table created successfully
$ sqlite3 MyDb.db 
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> .tables
Employee
sqlite> .exit

In the above program, we included the sqlite3.h header file to uses SQLite related functions. Here, we created the employee table in the "MyDb.db" database using the sqlite3_exec() function by passing a specified SQL statement.

C SQLite Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.