下面是一段示例代码:
#include<stdio.h>
#include "sqlite3.h"
intmain(){
sqlite3*db;
char*zErrMsg = NULL;
intrv;
charszSql[128] = { 0 };
sqlite3_stmt*stmt;
rv= sqlite3_open("test.db", &db);
if(rv ){
fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
sqlite3_close(db);
return1;
}
else
fprintf(stderr,"sqlite3_openOK\n");
//这里查询时,假定数据库中存在表test,并且有一列为COL1(text类型)
strcpy(szSql, "SELECT COL1 FROM test whereCOL1=?");
rv=sqlite3_prepare(db, szSql, 128, &stmt, NULL);
if(rv != SQLITE_OK ) {
fprintf(stderr,"sqlite3_prepare(%d):%s\n",rv,sqlite3_errmsg(db));
return-1;
}
rv=sqlite3_bind_text(stmt, 1, "VALUE1", strlen("VALUE1"), SQLITE_STATIC);
if(rv != SQLITE_OK ) {
fprintf(stderr, "sqlite3_bind_text(%d):%s\n",rv,sqlite3_errmsg(db));
return-1;
}
rv= sqlite3_step(stmt);
if((rv != SQLITE_OK) && (rv != SQLITE_DONE) && (rv != SQLITE_ROW) ) {
fprintf(stderr,"sqlite3_step(%d):%s\n",rv,sqlite3_errmsg(db));
return-1;
}//SQLITE_ROW为查询成功且有查询值的返回
while( rv == SQLITE_ROW ){
fprintf(stderr,"result:%s\n",sqlite3_column_text(stmt,0));
rv= sqlite3_step(stmt);
} //sqlite3_column_text(stmt,0)第二个参数为要显示的第几个通配符
rv=sqlite3_finalize(stmt);
if(rv != SQLITE_OK ) {
fprintf(stderr,"sqlite3_finalize(%d):%s\n",rv,sqlite3_errmsg(db));
return-1;
}
sqlite3_close(db);
return 0;
}