我正在尝试用c学习sqlite3 api,然后我创建了一个用于存储名称和电话的表,称为议程。然后我用3行填充它。我的下一步是创建以下c代码:
#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);
}
然后用gcc -o agenda agenda.c -lsqlite3 -Wall -ggdb
编译它。但我得到的结果总是:
Database connection okay!
Reading data...
Phone | Name
Rows count: 0
但实际上agenda.db
文件中有3行。我做错了什么?
答案 0 :(得分:9)
我相信你想要while (sqlite3_step(res) == SQLITE_ROW) {
而不是!=