Linux下sqlite数据库操作-<一> 表的检测,创建,删除。
表的检测,创建,删除。#include#include#include#include#includebool db_tableExists(sqlite3 *db, const char *tbname){int nRet;const char*szTail;sqlite3_stmt *pvm;c
·
<一> 表的检测,创建,删除。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
bool db_tableExists(sqlite3 *db, const char *tbname)
{
int nRet;
const char *szTail;
sqlite3_stmt *pvm;
char sql[1024];
sprintf(sql, "select count(*) from sqlite_master where type='table' and name='%s'", tbname);
szTail=0;
nRet = sqlite3_prepare(db, sql, -1, &pvm, &szTail);
//printf("nRet=%d SQLITE_OK=%d SQLITE_DONE=%d SQLITE_ROW=%d \n", nRet, SQLITE_OK, SQLITE_DONE,SQLITE_ROW);
if (nRet==SQLITE_OK)
{
nRet=sqlite3_step(pvm);
//printf("nRet=%d SQLITE_OK=%d SQLITE_DONE=%d SQLITE_ROW=%d \n", nRet, SQLITE_OK, SQLITE_DONE,SQLITE_ROW);
if (nRet==SQLITE_ROW)
{
int nCols = sqlite3_column_count(pvm);
//printf("nCols:%d\n", nCols);
if (nCols>=1)
{
return sqlite3_column_int(pvm,0)!=0;
}
}
}
return false;
}
int db_exeDML(sqlite3 *db, const char *sql)
{
char* szError=0;
int nRet = sqlite3_exec(db, sql, 0, 0, &szError);
if (nRet == SQLITE_OK)
{
return sqlite3_changes(db);
}
return SQLITE_ERROR;
}
int main(int argc, char **argv)
{
sqlite3 *db=0;
int nRet = sqlite3_open("temp.db",&db);
if (nRet)
{
fprintf(stderr,"can't open database: %s\n",sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}else{
printf("open database ok.\n");
}
if (!db_tableExists(db,"tmp"))
{
printf("create \"tmp\" table\n");
nRet=db_exeDML(db,"CREATE TABLE tmp( IP TEXT, VER TEXT, UID TEXT, FILE TEXT)");
printf("nRet=%d\n", nRet);
}else{
nRet=db_exeDML(db,"delete from tmp");
printf("nRet=%d\n", nRet);
}
sqlite3_close(db);
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)