C连接SQLite
时间:2011-05-22 来源:杨中科
// checkusername.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//sqlite3_exec的重载,避免穿那么多用不到的参数(纯C没有重载)
SQLITE_API int sqlite3_exec(sqlite3* db,const char *sql)
{
char *zErrMsg = 0;
return sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("Contenttype:text/html\n\n"); //根据HTTP协议,这里一定要有个空行。
sqlite3 *db;
int rc;
rc = sqlite3_open("D:\\greeninstall\\tinywebserver\\wwwroot\\rp.db3", &db);
if( rc!=SQLITE_OK )
{
printf( "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return -1;
}
/*rc = sqlite3_exec(db, "Insert into T_User(username,password) values('admin','123')");
if( rc !=SQLITE_OK )
{
printf("Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return -1;
}*/
sqlite3_stmt *pStmt;
//建立过程
rc = sqlite3_prepare(db, "select * from T_User where password=?", -1, &pStmt, 0);
if(rc != SQLITE_OK){
printf( "execute sql error: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return -1;
}
//绑定参数
if(sqlite3_bind_text(pStmt, 1, "123",-1,SQLITE_STATIC) != SQLITE_OK){
printf( "sqlite3_bind_int error: %s\n", sqlite3_errmsg(db));
goto test_exit;
}
// 多次执行过程
while(sqlite3_step(pStmt)!=SQLITE_DONE){
const unsigned char* name = sqlite3_column_text(pStmt,1);
const unsigned char* password = sqlite3_column_text(pStmt,2);
printf("%s=%s\n",name,password);
}
test_exit:
if(sqlite3_finalize(pStmt) != SQLITE_OK){
printf( "testPrepareStmt-sqlite3_finalize");
}
sqlite3_close(db);
printf("ok");
return 0;
}