C program to get SQLite version using 'SELECT' statement in Linux

Here, we are going to write a C program to get SQLite version using 'SELECT' statement in Linux.
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 get the SQLite version using the "SELECT" statement and then print the SQLITE version on the console screen.

Program/Source Code

The source code to get the SQLite version using the 'SELECT' statement is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to get SQLITE version using 
//"SELECT" statement in linux.

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

int main(void)
{
    sqlite3* db_ptr;
    sqlite3_stmt* stmt;

    int ret = 0;

    ret = sqlite3_open(":memory:", &db_ptr);

    if (ret != SQLITE_OK) {
        printf("\nDatabase opening error");
        sqlite3_close(db_ptr);
        return 1;
    }

    ret = sqlite3_prepare_v2(db_ptr, "SELECT SQLITE_VERSION()", -1, &stmt, 0);

    if (ret != SQLITE_OK) {
        printf("\nUnable to fetch data");
        sqlite3_close(db_ptr);
        return 1;
    }

    ret = sqlite3_step(stmt);

    if (ret == SQLITE_ROW)
        printf("SQLITE Version: %s\n", sqlite3_column_text(stmt, 0));

    sqlite3_finalize(stmt);
    sqlite3_close(db_ptr);

    return 0;
}

Output

$ gcc version2.c -o version2 -lsqlite3 -std=c99
$ ./version2
SQLITE Version: 3.31.1

Explanation

In the above program, we included the sqlite3.h header file to use SQLite related functions.

Here, we used sqlite_open() function to open a specified database. In sqlite_open() function we passed the ":memory:" as a database. The ":memory:" The :memory: is a special database name using which is used to open an in-memory database.

ret = sqlite3_prepare_v2(db_ptr, "SELECT SQLITE_VERSION()", -1, &stmt, 0);

The above function is used to compile the "SELECT" statement.

ret = sqlite3_step(stmt);

The above function is used to execute the specified select statement and get the resulted record.

printf("SQLITE Version: %s\n", sqlite3_column_text(stmt, 0));

The sqlite3_column_text() function is used to get the column value from the resulted record.

sqlite3_finalize(stmt);
sqlite3_close(db_ptr);

The above functions are used to close database properly.

C SQLite Programs »


Comments and Discussions!

Load comments ↻






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