Linux下SQLite数据库操作:表的检测,创建,删除。


  1. <一> 表的检测,创建,删除。  
  2.   
  3. #include <stdio.h>   
  4. #include <stdbool.h>   
  5. #include <stdlib.h>   
  6. #include <string.h>   
  7. #include <sqlite3.h>   
  8.   
  9. bool db_tableExists(sqlite3 *db, const char *tbname)  
  10. {  
  11.     int nRet;  
  12.     const char   *szTail;  
  13.     sqlite3_stmt *pvm;  
  14.     char sql[1024];  
  15.     sprintf(sql, "select count(*) from sqlite_master where type='table' and name='%s'", tbname);  
  16.   
  17.     szTail=0;  
  18.   
  19.     nRet = sqlite3_prepare(db, sql, -1, &pvm, &szTail);  
  20.   
  21.     //printf("nRet=%d SQLITE_OK=%d SQLITE_DONE=%d SQLITE_ROW=%d \n", nRet, SQLITE_OK, SQLITE_DONE,SQLITE_ROW);   
  22.   
  23.     if (nRet==SQLITE_OK)  
  24.     {  
  25.         nRet=sqlite3_step(pvm);  
  26.   
  27.         //printf("nRet=%d SQLITE_OK=%d SQLITE_DONE=%d SQLITE_ROW=%d \n", nRet, SQLITE_OK, SQLITE_DONE,SQLITE_ROW);   
  28.   
  29.         if (nRet==SQLITE_ROW)  
  30.         {  
  31.             int nCols = sqlite3_column_count(pvm);  
  32.             //printf("nCols:%d\n", nCols);   
  33.             if (nCols>=1)  
  34.             {  
  35.                 return sqlite3_column_int(pvm,0)!=0;  
  36.             }  
  37.         }  
  38.     }  
  39.   
  40.     return false;  
  41. }  
  42.   
  43. int db_exeDML(sqlite3 *db, const char *sql)  
  44. {  
  45.     char* szError=0;  
  46.     int nRet = sqlite3_exec(db, sql, 0, 0, &szError);  
  47.     if (nRet == SQLITE_OK)  
  48.     {  
  49.         return sqlite3_changes(db);  
  50.     }  
  51.     return SQLITE_ERROR;  
  52. }  
  53.   
  54.   
  55. int main(int argc, char **argv)  
  56. {  
  57.   
  58.     sqlite3 *db=0;  
  59.     int  nRet = sqlite3_open("temp.db",&db);  
  60.   
  61.     if (nRet)  
  62.     {  
  63.         fprintf(stderr,"can't open database: %s\n",sqlite3_errmsg(db));  
  64.         sqlite3_close(db);  
  65.         exit(1);  
  66.     }else{  
  67.         printf("open database ok.\n");  
  68.     }  
  69.   
  70.     if (!db_tableExists(db,"tmp"))  
  71.     {  
  72.         printf("create \"tmp\" table\n");  
  73.         nRet=db_exeDML(db,"CREATE TABLE tmp( IP TEXT, VER TEXT, UID TEXT, FILE TEXT)");  
  74.         printf("nRet=%d\n", nRet);  
  75.     }else{  
  76.         nRet=db_exeDML(db,"delete from tmp");  
  77.         printf("nRet=%d\n", nRet);  
  78.     }  
  79.   
  80.     sqlite3_close(db);  
  81.   
  82.     return 0;  
  83. }  

相关内容