Q:

C program to insert data into a database table in SQLite

0

C program to insert data into a database table in SQLite

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create an employee table and then insert data into the employee table using source code in Linux.

Program/Source Code:

The source code to insert data into a database table in Linux is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to insert data in a database table 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");
    }

    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;
}

Output:

$ gcc insert.c -o insert -lsqlite3 -std=c99
$ ./insert
Data inserted in employee table successfully
$ sqlite3 MyDb.db 
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> select * from employee;
101|Amit|15000
102|Arun|20000
103|Anup|22000
104|Ramu|9000

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now