Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data from sqlite with c

Tags:

c

database

sqlite

I am trying to learn the sqlite3 api with c, then I've created an table to store names and phones called agenda. Then I've populated it with 3 rows. My next step was create the following c code:

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

int main(int argc, char **argv)
{
  sqlite3 *db;
  sqlite3_stmt *res;
  const char *tail;
  int count = 0;

  if(sqlite3_open("agenda.db", &db))
  {
    sqlite3_close(db);
    printf("Can't open database: %s\n", sqlite3_errmsg(db));
    return(1);
  }

  printf("Database connection okay!\n");

  if(sqlite3_prepare_v2(db, "SELECT phone,name FROM agenda ORDER BY name", 128, &res, &tail) != SQLITE_OK)
  {
    sqlite3_close(db);
    printf("Can't retrieve data: %s\n", sqlite3_errmsg(db));
    return(1);
  }

  printf("Reading data...\n");

  printf("%16s | %32s\n", "Phone", "Name");

  while(sqlite3_step(res) != SQLITE_ROW)
  {
    printf("%16s | %32s\n",
           sqlite3_column_text(res, 0),
           sqlite3_column_text(res, 1));

    count++;
  }

  printf("Rows count: %d\n", count);

  sqlite3_finalize(res);

  sqlite3_close(db);

  return(0);
}

Then compiled it with gcc -o agenda agenda.c -lsqlite3 -Wall -ggdb. But the result I get is always:

Database connection okay!
Reading data...
           Phone |                             Name
Rows count: 0

But actually there are 3 rows in the agenda.db file. What am I doing wrong?

like image 312
Wanderson Silva Avatar asked Sep 15 '25 00:09

Wanderson Silva


1 Answers

I believe you want while (sqlite3_step(res) == SQLITE_ROW) { instead of !=

like image 107
GWW Avatar answered Sep 16 '25 15:09

GWW