Loading, please wait...

A to Z Full Forms and Acronyms

How to insert data into a database table in SQLite in C | C Programs

Mar 29, 2022 C programming, 3508 Views
How to insert data into a database table in SQLite in C | C Programs

How to insert data into a database table in SQLite in C | C Programs

We will create an employee table and then insert data into the employee table using source code in Linux.

#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");
    }

    char* sql_stmt = "DROP TABLE IF EXISTS Employee;"
                     "CREATE TABLE Employee(Eid INT, Ename TEXT, Salary INT);"
                     "INSERT INTO Employee VALUES(101, 'Amit', 15000);"
                     "INSERT INTO Employee VALUES(102, 'Arun', 20000);"
                     "INSERT INTO Employee VALUES(103, 'Anup', 22000);"
                     "INSERT INTO Employee VALUES(104, 'Ramu', 09000);";

    ret = sqlite3_exec(db_ptr, sql_stmt, 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("Data inserted in employee table successfully\n");
    sqlite3_close(db_ptr);

    return 0;
}
A to Z Full Forms and Acronyms