Q:

C program to get the last row id of a database table in SQLite

belongs to collection: C SQLite Programs

0

C program to get the last row id of 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 insert records into the employee table using source code and then print the last row id on the console screen.

Program/Source Code:

The source code to get the last row id of a database table in SQLite is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to get the last row id of a database table in SQLite.

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

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

    int ret = 0;
    int last_row_id = 0;

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

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

    char* sql_stmt = "INSERT INTO Employee VALUES(201, 'Vikas', 25000);"
                     "INSERT INTO Employee VALUES(202,  'Varun', 30000);";

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

    last_row_id = sqlite3_last_insert_rowid(db_ptr);
    printf("Last row id in employee table is: %d\n", last_row_id);

    sqlite3_close(db_ptr);
    return 0;
}

Output:

$ gcc rowid.c -o rowid -lsqlite3 -std=c99
$ ./rowid 
Last row id in employee table is: 2

In the above program, we included the sqlite3.h header file to uses SQLite related functions. Here, we inserted two records into the employee table in the "MyDb.db" database using sqlite3_exec() by passing a specified SQL statement. Here, we used the sqlite3_last_insert_rowid() function to get the last row id and print row id on the console screen.

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

total answers (1)

C program to get record from a database table usin... >>
<< C program to get records from a database table in ...