IOS中的sqlite数据库的使用

 

[置顶] IOS中的sqlite数据库的使用

分类: 数据库技术 IOS开发 36人阅读 评论(0) 收藏 举报
 
http://blog.csdn.net/cubepeng/article/details/7336091
 
 

sqlite在移动客户端的开发非常常见,我之前做过一个ios项目中也用到,无耐技术水平有限,做的不是很好!但是一查网上这方面的总结不是很多,可能大牛们都忙着赚钱去了,我就献丑将我在项目中用到的东西贡献出来,有什么不好的地方请指教。值得说明的是我是看了某个网站贴出的demo而稍作改进,若此君不小心看到本篇小作,请指出,如有需要可以删除此文。下面开始介绍我的做的东西:

1.用到主要的函数有sqlite3_open,sqlite3_close,sqlite3_exe这里我不解释这些函数的用法了(http://www.cppblog.com/woaidongmao/archive/2009/06/23/88361.html,有详细介绍),直接进入正题。

2.这个例子里面涉及如下几个文件,DatabaseConnection,DatabaseStatement,DataBaseCenter.在这个demo中我只要用到一个数据库



DatabaseConnection.h

  1. #import <Foundation/Foundation.h>  
  2. #import "sqlite3.h"  
  3. #import "DataStatement.h"  
  4.   
  5. @interface DataConnection : NSObject  
  6. //建表   
  7. +(void)exeCreate:(NSString*)createString;  
  8. +(sqlite3*)sharedDataBase;      //访问单例   
  9. +(void)closeDataBase;              //关闭数据库连接,置空句柄  
  10. +(void)beginTransaction;          //开始事务  
  11. +(void)commitTransaction;      //提交事务  
  12. + (DataStatement*)statementWithQuery:(const char*)sql; //初始化一个连接  
  13. +(void)alert; //提出警告  
  14. +(int)getRowsWithQury:(const char*)sql;  //获取select语句中结果数据的行数  
  15. @end  

DatabaseConnection.m

  1. #import "DataConnection.h"  
  2. #define DATABASENAME @"Demo.db"  
  3.   
  4. static sqlite3 *dataBaseInstance = nil;  
  5. @implementation DataConnection  
  6. +(void)exeCreate:(NSString*)createString  
  7. {  
  8.     char *errorMsg;  
  9.     if (sqlite3_exec(dataBaseInstance, [createString UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK)  
  10.     {  
  11.         NSAssert1(0, @"can not create users table,'%s'.",errorMsg);  
  12.     }  
  13.     [self closeDataBase];  
  14. }  
  15. +(sqlite3*)openDataBase:(NSString*)dataBaseName  
  16. {  
  17.     NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  18.     NSString * path = [array objectAtIndex:0];  
  19.     NSString * databasePath = [path stringByAppendingPathComponent:dataBaseName];  
  20.     if (sqlite3_open([databasePath UTF8String], &dataBaseInstance)!=SQLITE_OK)  
  21.     {  
  22.         NSLog(@"can not open the database:%@",sqlite3_errmsg(dataBaseInstance));  
  23.         sqlite3_close(dataBaseInstance);  
  24.         return nil;  
  25.     }  
  26.     return dataBaseInstance;  
  27.       
  28. }  
  29. +(sqlite3*)sharedDataBase  
  30. {  
  31.     if (nil == dataBaseInstance) {  
  32.         @synchronized(self)  
  33.         {  
  34.             dataBaseInstance = [self openDataBase:DATABASENAME];  
  35.               
  36.         }  
  37.         if (nil == dataBaseInstance) {  
  38.             [self  createEditableCopyofDataBaseIfNeeded:YES];   
  39.         }  
  40.   
  41.     }  
  42.     return dataBaseInstance;  
  43. }  
  44. +(void)commitTransaction  
  45. {  
  46.     char *errMessage;  
  47.     sqlite3_exec(dataBaseInstance, "COMMIT", nil, nil, &errMessage);  
  48. }  
  49. +(void)beginTransaction  
  50. {  
  51.     char *errMessage;  
  52.     sqlite3_exec(dataBaseInstance, "BEGIN", nil, nil, &errMessage);  
  53. }  
  54.   
  55. +(DataStatement*)statementWithQuery:(const char*)sql  
  56. {  
  57.     [self sharedDataBase];  
  58.     DataStatement *dataStatement = [DataStatement statementWithDB:dataBaseInstance withQuery:sql];  
  59.     return dataStatement;  
  60.   }  
  61. +(void)closeDataBase  
  62. {  
  63.     sqlite3_close(dataBaseInstance);  
  64.     dataBaseInstance = nil;                  //数据库句柄一定要置空,不然重新建立连接的时候会有问题  
  65. }  
  66. +(void)alert  
  67. {  
  68.     NSString *errorString = [NSString stringWithUTF8String:   sqlite3_errmsg(dataBaseInstance)];  
  69.     CLog(@"alert message:%@",errorString);   
  70. }  

Datastatement.h

  1. #import <Foundation/Foundation.h>  
  2. #import "sqlite3.h"  
  3.   
  4. @interface DataStatement : NSObject  
  5. {  
  6.     sqlite3_stmt* stmt;  
  7. }  
  8. +(id)statementWithDB:(sqlite3*)DB withQuery:(const char *)sql;  
  9. -(id)initWithDB:(sqlite3*)db withQuery:(const char *)sql;  
  10. // method  
  11. - (int)step;  
  12. - (void)reset;  
  13. - (int)getResultCount;  
  14.   
  15. // Getter  
  16. - (NSString*)getString:(int)index;  
  17. - (int)getInt32:(int)index;  
  18. - (long long)getInt64:(int)index;  
  19. - (NSData*)getData:(int)index;  
  20. - (double)getDouble:(int)index;  
  21.   
  22. // Binder  
  23. - (void)bindString:(NSString*)value forIndex:(int)index;  
  24. - (void)bindInt32:(int)value forIndex:(int)index;  
  25. - (void)bindInt64:(long long)value forIndex:(int)index;  
  26. - (void)bindData:(NSData*)data forIndex:(int)index;  
  27. - (void)bindDouble:(double)value forIndex:(int)index;  
  28. @end  

Datastatement.m

  1. //  
  2. //  DataStatement.m  
  3. //  mainPage  
  4. //  
  5. //  Created by myiee on 11-11-3.  
  6. //  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import "DataStatement.h"  
  10.   
  11. @implementation DataStatement  
  12. -(void)dealloc  
  13. {  
  14.     [super dealloc];  
  15.     sqlite3_finalize(stmt);  
  16. }  
  17. -(id)initWithDB:(sqlite3 *)db withQuery:(const char *)sql  
  18. {  
  19.     self = [super init];  
  20.     if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL)!=SQLITE_OK) {  
  21.         NSAssert2(0, @"can not compare '%s',(%s)", sql, sqlite3_errmsg(db));  
  22.     }  
  23.     return self;  
  24. }  
  25. +(id)statementWithDB:(sqlite3 *)DB withQuery:(const char *)sql  
  26. {  
  27.     return [[[DataStatement alloc]initWithDB:DB withQuery:sql]autorelease];  
  28. }  
  29.   
  30. -(int)step  
  31. {  
  32.     return  sqlite3_step(stmt);  
  33. }  
  34. -(void)reset  
  35. {  
  36.     sqlite3_reset(stmt);  
  37. }  
  38. - (int)getResultCount  
  39. {  
  40.    return  sqlite3_column_count(stmt);  
  41. }  
  42. -(NSString*)getString:(int)index  
  43. {  
  44.     if (NULL != (char*)sqlite3_column_text(stmt, index)) {  
  45.         return [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, index)];  
  46.     }  
  47.     else  
  48.         return nil;  
  49. }  
  50. -(int)getInt32:(int)index  
  51. {  
  52.     return sqlite3_column_int(stmt, index);  
  53. }  
  54. -(long long)getInt64:(int)index  
  55. {  
  56.     return sqlite3_column_int64(stmt, index);  
  57. }  
  58. -(NSData*)getData:(int)index  
  59. {  
  60.     int length =  sqlite3_column_bytes(stmt, index);  
  61.     return [NSData dataWithBytes:sqlite3_column_blob(stmt, index) length:length];  
  62. }  
  63. -(double)getDouble:(int)index  
  64. {  
  65.     return sqlite3_column_double(stmt, index);  
  66. }  
  67. -(void)bindData:(NSData *)data forIndex:(int)index  
  68. {  
  69.     sqlite3_bind_blob(stmt, index, data.bytes, data.length, SQLITE_TRANSIENT);  
  70. }  
  71. -(void)bindString:(NSString *)value forIndex:(int)index  
  72. {  
  73.     sqlite3_bind_text(stmt, index,[value UTF8String] , -1, SQLITE_TRANSIENT);  
  74. }  
  75. -(void)bindInt32:(int)value forIndex:(int)index  
  76. {  
  77.     sqlite3_bind_int(stmt, index,value);  
  78. }  
  79. -(void)bindInt64:(long long)value forIndex:(int)index  
  80. {  
  81.     sqlite3_bind_int64(stmt, index, value);  
  82. }  
  83. -(void)bindDouble:(double)value forIndex:(int)index  
  84. {  
  85.     sqlite3_bind_double(stmt, index, value);  
  86. }  
  87. @end  
DatabaseCenter.h

  1. #import <Foundation/Foundation.h>  
  2. #import "sqlite3.h"  
  3. //#import "Users.h"  
  4. #import "DataConnection.h"  
  5. #import "DataStatement.h"  
  6. @interface DataBaseCenter : NSObject  
  7. {  
  8.     sqlite3_stmt *stmt;  
  9. }  
  10. + (void)createDatabase;  
  11. //user  
  12. + (id)getLastLoginUser;  
  13. + (BOOL)updateUser:(NSDictionary*)dictionary;  
  14. + (id)getUserWithName:(NSString*)name;  
  15. @end  

DatabaseCenter.m

  1. +(void)createDatabase  
  2. {  
  3.     [DataConnection sharedDataBase];  
  4.     NSString *createUser   = @"create table if not exists user(userId integer primary key,name text not null,password text not null,flag integer not null);";  
  5.    //这个数据库中只建立了一个user的数据表,当flag为1的时候代表这条用户的数据纪录是最后一个合法登陆的数据用户  
  6.     [DataConnection exeCreate:createDataString];  
  7. }  
  8. + (id)getLastLoginUser  
  9. {  
  10.     static DataStatement *stmt = nil;  
  11.     if (!stmt)   
  12.     {  
  13.         stmt = [DataConnection statementWithQuery:"select * from user where flag = 1"];  
  14.         [stmt retain];  
  15.     }  
  16.     if (SQLITE_ROW != [stmt step]) {  
  17.         [stmt reset];  
  18.         return nil;  
  19.     }  
  20.     NSString *userName = [stmt getString:1];  
  21.     NSString *password = [stmt getString:2];  
  22.     NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:userName,@"name",password,@"password", nil];  
  23.     return [dic autorelease];  
  24. }  
  25. + (BOOL)updateUser:(NSDictionary*)dictionary  //将当前的的数据的flag更新为1 ,其他置为0,当前的用户数据不存在的时候插入到表中  
  26. {  
  27.     NSDictionary *dic  = [dictionary retain];  
  28.     NSString *userName = [dic objectForKey:@"name"];  
  29.     NSString *password = [dic objectForKey:@"password"];  
  30.     int flag           = [[dic objectForKey:@"flag"]intValue];  
  31.       
  32.     NSString *selectString = [NSString stringWithFormat:@"select * from user where name = '%@'",userName];  
  33.     const char *cString      = [selectString cStringUsingEncoding:NSUTF8StringEncoding ];  
  34.     unsigned int r = [DataConnection getRowsWithQury:cString];  
  35.     DataStatement *stmt = nil;  
  36.     
  37.     if (!stmt) {  
  38.         stmt  = [DataConnection statementWithQuery:"update user set flag = 0 where flag != 0"];  
  39.         [stmt retain];  
  40.     }  
  41.     if (SQLITE_DONE != [stmt step]) {  
  42.         [stmt release];  
  43.         [stmt reset];  
  44.         stmt = nil;  
  45.         return NO;  
  46.     }  
  47.     [stmt release];  
  48.     stmt = nil;  
  49.     if (r ==1 ) {//当之前已经存在该数据的时候更新变为1  
  50.         NSString *stmtString = [NSString stringWithFormat:@"update user set flag = 1 where name = '%@'",userName];  
  51.         stmt  = [DataConnection statementWithQuery:[stmtString UTF8String]];  
  52.         [stmt retain];  
  53.         if (SQLITE_DONE != [stmt step]) {  
  54.             [stmt release];  
  55.             [stmt reset];  
  56.             stmt = nil;  
  57.             return NO;  
  58.         }  
  59.         [stmt release];  
  60.     }  
  61.     else   
  62.     {  
  63.         stmt = nil;  
  64.         if (!stmt) {  
  65.             stmt = [DataConnection statementWithQuery:"insert or replace into user(name,password,flag) values(?,?,?)"];  
  66.             [stmt retain];  
  67.         }  
  68.         [stmt bindString:userName forIndex:1];  
  69.         [stmt bindString:password forIndex:2];  
  70.         [stmt bindInt32:flag forIndex:3];  
  71.         if (SQLITE_DONE != [stmt step]) {  
  72.             [stmt reset];  
  73.             [stmt release];  
  74.             return NO;  
  75.         }  
  76.         [stmt release];  
  77.      }  
  78.     return YES;  
  79.       
  80. }  
  81. //根据用户名获取用户的数据  
  82. + (id)getUserWithName:(NSString *)name  
  83. {  
  84.     DataStatement *stmt = nil;  
  85.     NSString *selectString = [NSString stringWithFormat:@"select * from user where name = %@",name];  
  86.     const char *cString    = [selectString cStringUsingEncoding:NSUTF8StringEncoding];  
  87.     if (!stmt)   
  88.     {  
  89.         stmt = [DataConnection statementWithQuery:cString];  
  90.         [stmt retain];  
  91.     }  
  92.     if (SQLITE_ROW != [stmt step]) {  
  93.         [stmt reset];  
  94.         return nil;  
  95.     }  
  96.     NSString *userName = [stmt getString:1];  
  97.     NSString *password = [stmt getString:2];  
  98.     NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:userName,@"name",password,@"password", nil];  
  99.     return [dic autorelease];  
  100.       
  101. }  
4.现在经过简单的封装,我们就能用数据库了

现在我们能在任何一个地方使用这个单例了,现在我们新建一个文件TestDatabase文件中的使用他

      
  1. - (void)loadView  
  2. {  
  3.       [super loadView];  
  4.       [DataBasecenter createDatabase];  
  5.       NSDictionary *dic = [NSDictionary dicionaryValueAndkeys:@"name",@"name",@"1234567",@"password",@"1",@"flag"];  
  6.      [DataBaseCenter updateUser:dic];  
  7.       }  

这样我们就能使用数据库了,其实挺简单的。

4.我在这个例子中只有一个数据库,所以用单例很方便,当然你想建立多个数据库,那也是很简单,一个数据库对应的一个数据库connection,一个connection可以对应多个statement,我这样的封装适合单个数据库,你也可以封装成工厂的方式,见前面我对xml解析的一文,也是很简单的。

总结:对sqlite的使用,我之前看到一个很好的例子,我将转过来作为一个单独的系列。

注:转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值