ios 封装sqllite3接口

时间:2022-09-28 23:06:03

261人阅读 评论(0) 收藏 举报

  1. //   
  2. #import <Foundation/Foundation.h>    
  3. #import "sqlite3.h"    
  4. @interface Sqllib : NSObject   
  5. {    
  6.     sqlite3 *m_sql;    
  7.     NSString *m_dbName;    
  8. }   
  9. @property(nonatomic)sqlite3*  m_sql;    
  10. @property(nonatomic,retain)NSString*  m_dbName;  
  11.     
  12. -(id)initWithDbName:(NSString*)dbname;    
  13. -(BOOL)openOrCreateDatabase:(NSString*)DbName;    
  14. -(BOOL)createTable:(NSString*)sqlCreateTable;    
  15. -(void)closeDatabase;    
  16. -(BOOL)InsertTable:(NSString*)sqlInsert;    
  17. -(BOOL)UpdataTable:(NSString*)sqlUpdata;    
  18. -(NSArray*)querryTable:(NSString*)sqlQuerry;    
  19. -(NSArray*)querryTableByCallBack:(NSString*)sqlQuerry;    
  20. @end  
  21.    
  22. //   
  23. #import "sqllib.h"     
  24. @implementation Sqllib   
  25.    
  26. @synthesize m_sql;    
  27. @synthesize m_dbName;  
  28.     
  29. -(id) initWithDbName:(NSString*)dbname    
  30. {    
  31.     self = [super init];    
  32.     if (self != nil) {    
  33.        if ([self openOrCreateDatabase:dbname]) {    
  34.             [self closeDatabase];    
  35.         }    
  36.     }    
  37.     return self;    
  38. }    
  39. -(id) init    
  40. {    
  41.     NSAssert(0,@"Never Use this.Please Call Use initWithDbName:(NSString*)");    
  42.     return nil;    
  43. }    
  44. -(void) dealloc    
  45. {    
  46.     self.m_sql = nil;    
  47.     self.m_dbName =nil;    
  48.     [super dealloc];    
  49. }    
  50. //创建数据库     
  51. -(BOOL)openOrCreateDatabase:(NSString*)dbName    
  52. {    
  53.     self.m_dbName = dbName;    
  54.     NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);    
  55.     NSString *documentsDirectory = [path objectAtIndex:0];    
  56.     if(sqlite3_open([[documentsDirectorystringByAppendingPathComponent:dbName] UTF8String],&m_sql) !=SQLITE_OK)    
  57.     {    
  58.         NSLog(@"创建数据库失败");    
  59.         return NO;    
  60.     }    
  61.     return YES;    
  62. }   
  63. //关闭数据库     
  64. -(void)closeDatabase    
  65. {    
  66.     sqlite3_close(self.m_sql);     
  67. }   
  68.    
  69. //创建表    
  70. -(BOOL)createTable:(NSString*)sqlCreateTable    
  71. {    
  72.     if (![selfopenOrCreateDatabase:self.m_dbName]) {    
  73.         return NO;    
  74.     }    
  75.     char *errorMsg;    
  76.     if (sqlite3_exec (self.m_sql, [sqlCreateTable UTF8String],NULL, NULL, &errorMsg) != SQLITE_OK)    
  77.     {    
  78.         NSLog(@"创建数据表失败:%s",errorMsg);    
  79.         return NO;    
  80.     }    
  81.     [selfcloseDatabase];    
  82.     return YES;    
  83. }     
  84. //插入表      
  85. -(BOOL)InsertTable:(NSString*)sqlInsert    
  86. {    
  87.     if (![selfopenOrCreateDatabase:self.m_dbName]) {    
  88.         return NO;    
  89.     }    
  90.    char* errorMsg = NULL;    
  91.     if(sqlite3_exec(self.m_sql, [sqlInsertUTF8String],0, NULL, &errorMsg) ==SQLITE_OK)    
  92.   {    
  93.     [selfcloseDatabase];    
  94.     returnYES;  
  95.   }    
  96.     else   
  97.     {    
  98.         printf("更新表失败:%s",errorMsg);    
  99.         [selfcloseDatabase];    
  100.         return NO;    
  101.     }    
  102.     return YES;    
  103. }    
  104. //更新表      
  105. -(BOOL)UpdataTable:(NSString*)sqlUpdata  
  106. {    
  107.  if (![selfopenOrCreateDatabase:self.m_dbName])   
  108.  {    
  109.    return NO;    
  110.  }    
  111.  char *errorMsg;    
  112.  if (sqlite3_exec (self.m_sql, [sqlUpdata UTF8String],0, NULL, &errorMsg) !=SQLITE_OK)    
  113.  {    
  114.   [selfcloseDatabase];    
  115.   returnYES;    
  116.  }  
  117.  else   
  118.  {    
  119.   returnNO;    
  120.  }      
  121.  return YES;    
  122. }    
  123. //查询表    
  124. -(NSArray*)querryTable:(NSString*)sqlQuerry    
  125. {    
  126.     if (![selfopenOrCreateDatabase:self.m_dbName]) {    
  127.         return nil;    
  128.     }    
  129.     int row = 0;    
  130.     int column = 0;    
  131.     char*    errorMsg = NULL;    
  132.     char**    dbResult = NULL;    
  133.     NSMutableArray*    array = [[NSMutableArrayalloc] init];    
  134.     if(sqlite3_get_table(m_sql, [sqlQuerryUTF8String], &dbResult, &row,&column,&errorMsg ) == SQLITE_OK)    
  135.     {    
  136.        if (0 == row) {    
  137.             [self closeDatabase];    
  138.             return nil;    
  139.         }    
  140.         int index = column;    
  141.         for(int i =0; i < row ; i++ ) {      
  142.             NSMutableDictionary*    dic = [[NSMutableDictionaryalloc] init];    
  143.             for(int j =0 ; j < column; j++ ) {    
  144.                 if (dbResult[index]) {    
  145.                     NSString*    value = [[NSStringalloc] initWithUTF8String:dbResult[index]];    
  146.                     NSString*    key = [[NSStringalloc] initWithUTF8String:dbResult[j]];    
  147.                     [dic setObject:value forKey:key];    
  148.                     [value release];    
  149.                     [key release];    
  150.                 }    
  151.                 index ++;    
  152.             }     
  153.             [array addObject:dic];    
  154.             [dic release];    
  155.         }    
  156.     }else {    
  157.         printf("%s",errorMsg);    
  158.         [selfcloseDatabase];    
  159.         return nil;    
  160.     }    
  161.     [selfcloseDatabase];    
  162.     return [array autorelease];    
  163. }    
  164. //select      
  165. int processData(void* arrayResult,int columnCount,char** columnValue,char** columnName)    
  166. {    
  167.     int i;     
  168.     NSMutableDictionary* dic = [[NSMutableDictionaryalloc] init];    
  169.     for( i = 0 ; i < columnCount; i ++ )     
  170.     {     
  171.        if (columnValue[i])   
  172.        {    
  173.             NSString* key = [[NSStringalloc] initWithUTF8String:columnName[i]];    
  174.             NSString* value = [[NSStringalloc] initWithUTF8String:columnValue[i]];    
  175.             [dic setObject:value forKey:key];    
  176.         }    
  177.     }     
  178.     [(NSMutableArray*)arrayResult addObject:dic];    
  179.     [dic release];    
  180.     return 0;     
  181. }    
  182. //select      
  183. -(NSArray*)querryTableByCallBack:(NSString*)sqlQuerry    
  184. {    
  185.     if (![selfopenOrCreateDatabase:self.m_dbName])   
  186.     {    
  187.         return nil;    
  188.     }    
  189.     char*    errorMsg = NULL;    
  190.     NSMutableArray* arrayResult = [[NSMutableArrayalloc] init];    
  191.     if (sqlite3_exec(self.m_sql,[sqlQuerryUTF8String],processData,(void*)arrayResult,&errorMsg) !=SQLITE_OK)   
  192.     {    
  193.         printf("查询出错:%s",errorMsg);    
  194.     }    
  195.     [selfcloseDatabase];    
  196.     return [arrayResult autorelease];    
  197. }   
  198.    
  199. @end  
  200.    
  201.    
  202. //   
  203. /*IOS开发中sqlite数据库的使用方法。 
  204. *sqlite数据库初始化,复制到用户目录,并判断是否数据库已经存在,或者复制是否成功; 
  205. *在AppDelegate.m中输入以下代码,以便复制预置数据库到指定doucment目录 
  206. */  
  207. - (BOOL) initializeDb   
  208. {    
  209.  NSLog (@"initializeDB");  
  210.  NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    
  211.  NSString *documentFolderPath = [searchPaths objectAtIndex: 0];    
  212.  //查看文件目录     
  213.  NSLog(@"%@",documentFolderPath);    
  214.  dbFilePath = [documentFolderPath stringByAppendingPathComponent:@"shopping.db"];  
  215.  [dbFilePath retain];      
  216.  if (! [[NSFileManager defaultManager] fileExistsAtPath: dbFilePath])   
  217.  {     
  218.   NSString *backupDbPath = [[NSBundle mainBundle] pathForResource:@"shopping" ofType:@"db"];    
  219.   if (backupDbPath == nil)   
  220.   {      
  221.     return NO;    
  222.   }   
  223.   else   
  224.   {    
  225.     BOOL copiedBackupDb = [[NSFileManager defaultManager] copyItemAtPath:backupDbPath toPath:dbFilePath error:nil];    
  226.     if (! copiedBackupDb)   
  227.     {   
  228.       return NO;    
  229.     }    
  230.   }    
  231.  }    
  232.  return YES;    
  233. }    
  234. - (void)applicationDidFinishLaunching:(UIApplication *)application   
  235. {    
  236.   if (! [self initializeDb])   
  237.   {    
  238.    NSLog (@"couldn't init db");    
  239.    return;    
  240.   }        
  241.     [window addSubview:tabBarController.view];    
  242. }