开发者

Retrieve data from sqlite with c

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");

开发者_如何学Go  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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜