Q:

C program to get record from a database table using parameterized SELECT query in SQLite

belongs to collection: C SQLite Programs

0

C program to get record from a database table using parameterized SELECT query 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 get records from the employee table using source code and print all records on the console screen.

Program/Source Code:

The source code to get records from a database table using parameterized SELECT query in Linux is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

// C program to get record from a database table using 
//parameterized SELECT query in linux.

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

int main(void)
{
    sqlite3* db_ptr;
    sqlite3_stmt* stmt;
    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[64];

    strcpy(sql_stmt, "SELECT * FROM Employee where eid=");
    strcat(sql_stmt, "201");

    ret = sqlite3_prepare_v2(db_ptr, sql_stmt, -1, &stmt, 0);

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

    printf("Employee records\n");
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        printf("%s %s %s\n", sqlite3_column_text(stmt, 0), sqlite3_column_text(stmt, 1), sqlite3_column_text(stmt, 2));
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db_ptr);

    return 0;
}

Output:

$ gcc select.c -o select -lsqlite3 -std=c99
$ ./select
Employee records
201 Vikas 25000

In the above program, we included the sqlite3.h header file to uses SQLite related functions. Here, we get a record of the employee table in the "MyDb.db" database using a specified parameterized SELECT query.

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.

while(sqlite3_step(stmt)==SQLITE_ROW)
{
    printf("%s %s %s\n", sqlite3_column_text(stmt, 0),
    sqlite3_column_text(stmt, 1),
    sqlite3_column_text(stmt, 2));
}

In the above code, we get records from the employee table one by one and then print employee records on the console screen.

sqlite3_finalize(stmt);
sqlite3_close(db_ptr);

The above functions are used to close database properly.

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

total answers (1)

C program to insert an image data into SQLite tabl... >>
<< C program to get the last row id of a database tab...