iOS 数据持久化四-SQLite3

iOS中有五种持久化数据的方式:属性列表、对象归档、NSUserDefaults、SQLite3和Core Data


SQLite3的数据类型

数据库在应用中最常用的,方便说数据的存取。

所有存在Sqlite 3.0版本当中的数据都拥有以下之一的数据类型:
空(NULL):该值为空
整型(INTEGEER):有符号整数,按大小被存储成1,2,3,4,6或8字节。
实数(REAL):浮点数,以8字节指数形式存储。
文本(TEXT):字符串,以数据库编码方式存储(UTF-8, UTF-16BE 或者 UTF-16-LE)。
BLOB:BLOB数据不做任何转换,以输入形式存储。

在关系数据库中,CLOB和BLOB类型被用来存放大对象。BOLB表示二进制大对象,这种数据类型通过用来保存图片,图象,视频等。CLOB表示字符大对象,能够存放大量基于字符的数据。


iOS中数据库SQLite3的使用

具体使用方法如下:

1.添加开发包libsqlite3.0.dylib

首先是设置项目文件,在项目中添加iPhone版的sqlite3的数据库的开发包,在项目下的Frameworks点击右键,然后选择libsqlite3.0.dylib文件。


libsqlite3.0.dylib文件地址: 
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/usr/lib/libsqlite3.0.dylib

2.有码有真相:

加入FMDB这个第三方库文件,项目编程开始。

AppDelegate.h文件

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  AppDelegate.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-22.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. @interface AppDelegate : UIResponder <UIApplicationDelegate>  
  12.   
  13. @property (strongnonatomicUIWindow *window;  
  14.   
  15. /** 
  16.  *  @brief  在状态栏处显示的提示框 
  17.  * 
  18.  *  @param string   显示的字符串 
  19.  *  @param duration 显示的时长 
  20.  */  
  21. + (void)showStatusWithText:(NSString *)string duration:(NSTimeInterval)duration;  
  22.   
  23. @end  

AppDelegate.m文件

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  AppDelegate.m  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-22.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10. #import "RootViewController.h"  
  11.   
  12. @interface AppDelegate ()  
  13.   
  14. @property (strongnonatomicUIWindow *statusWindow;  
  15. @property (retainnonatomicUILabel *statusLabel;  
  16.   
  17. - (void)dismissStatusLabel;  
  18.   
  19. @end  
  20.   
  21. @implementation AppDelegate  
  22.   
  23. - (void)dealloc  
  24. {  
  25.     [self.statusWindow release];  
  26.     [self.statusLabel release];  
  27.       
  28.     [_window release];  
  29.     [super dealloc];  
  30. }  
  31.   
  32. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  33. {  
  34.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  35.    
  36.     self.statusWindow = [[UIWindow alloc] initWithFrame:CGRectZero];  
  37.     self.statusWindow.backgroundColor = [UIColor clearColor];  
  38.     self.statusWindow.windowLevel = UIWindowLevelStatusBar + 1;  
  39.   
  40.     self.statusLabel = [[UILabel alloc] initWithFrame:CGRectZero];  
  41.     self.statusLabel.backgroundColor = [UIColor clearColor];  
  42.     self.statusLabel.textColor = [UIColor whiteColor];  
  43.     self.statusLabel.font = [UIFont systemFontOfSize:13];  
  44.     [self.statusWindow addSubview:self.statusLabel];  
  45.     [self.statusWindow makeKeyAndVisible];  
  46.       
  47.     RootViewController *rootVC = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];  
  48.     UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:rootVC];  
  49.     [rootVC release];  
  50.       
  51.     self.window.rootViewController = rootNav;  
  52.     [rootNav release];  
  53.       
  54.     // Override point for customization after application launch.  
  55.     self.window.backgroundColor = [UIColor whiteColor];  
  56.     [self.window makeKeyAndVisible];  
  57.     return YES;  
  58. }  
  59.   
  60. #pragma mark - Custom methods  
  61.   
  62. - (void)dismissStatusLabel  
  63. {  
  64.     CGRect rect = self.statusWindow.frame;  
  65.     rect.origin.y -= rect.size.height;  
  66.     [UIView animateWithDuration:0.8 animations:^{  
  67.         self.statusWindow.frame = rect;  
  68.     }];  
  69. }  
  70.   
  71. /** 
  72.  *  @brief  在状态栏处显示的提示框 
  73.  * 
  74.  *  @param string   显示的字符串 
  75.  *  @param duration 显示的时长 
  76.  */  
  77. + (void)showStatusWithText:(NSString *)string duration:(NSTimeInterval)duration  
  78. {  
  79.     AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;  
  80.       
  81.     delegate.statusLabel.text = string;  
  82.     [delegate.statusLabel sizeToFit];  
  83.     CGRect rect = [UIApplication sharedApplication].statusBarFrame;  
  84.     CGFloat width = delegate.statusLabel.frame.size.width;  
  85.     CGFloat height = rect.size.height;  
  86.     rect.origin.x = rect.size.width = width - 5;  
  87.     rect.size.width = width;  
  88.     delegate.statusWindow.frame = rect;  
  89.     delegate.statusLabel.backgroundColor = [UIColor blackColor];  
  90.     delegate.statusLabel.frame = CGRectMake(1000, width, height);  
  91.     duration = (duration < 1.0 ? 1.0 : duration);  
  92.     duration = (duration > 4.0 ? 4.0 : duration);  
  93.     [delegate performSelector:@selector(dismissStatusLabel)];  
  94. }  
  95.   
  96. @end  

使用FMDB第三方库,数据库管理文件


[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  DBManager.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. #import "FMDatabaseAdditions.h"  
  12.   
  13. @class FMDatabase;  
  14.   
  15. /** 
  16.  *  @brief 对数据连接进行管理,包括连接,关闭连接 
  17.  *  可以建立长连接 
  18.  * 
  19.  */  
  20. @interface DBManager : NSObject{  
  21.     NSString *_dbPath;  
  22. }  
  23.   
  24. @property (readonlynonatomicFMDatabase *dataBase;  
  25.   
  26. //单例模式  
  27. + (DBManager *)defaultDBManager;  
  28.   
  29. //关闭数据库  
  30. - (void)close;  
  31.   
  32. @end  

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  DBManager.m  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import "DBManager.h"  
  10. #import "FMDatabase.h"  
  11.   
  12. //#define kDefaultDBName @"user.sqlite"  
  13. #define kDefaultDBName @"user.db"  
  14.   
  15. @interface DBManager ()  
  16.   
  17. @end  
  18.   
  19. static DBManager *_sharedDBManager;  
  20.   
  21. @implementation DBManager  
  22.   
  23. - (void)dealloc  
  24. {  
  25.     [self close];  
  26.       
  27.     [super dealloc];  
  28. }  
  29.   
  30. - (id)init  
  31. {  
  32.     if (self = [super init]) {  
  33.         int state = [self initializeDBWithName:kDefaultDBName];  
  34.         if (-1 == state) {  
  35.             NSLog(@"数据库初始化失败!");  
  36.         }else {  
  37.             NSLog(@"数据库初始化成功!");  
  38.         }  
  39.     }  
  40.     return self;  
  41. }  
  42.   
  43. - (int)initializeDBWithName:(NSString *)name  
  44. {  
  45.     if (!name) {  
  46.         return -1;  //数据库创建失败  
  47.     }  
  48.       
  49.     //沙盒Doc目录  
  50.     NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  51.     _dbPath = [doc stringByAppendingString:[NSString stringWithFormat:@"/%@", name]];  
  52.     NSFileManager *fileManager = [NSFileManager defaultManager];  
  53.     BOOL exist = [fileManager fileExistsAtPath:_dbPath];  
  54.     [self connect];  
  55.     return (exist == YES ? 0 : 1);  
  56. }  
  57.   
  58. //连接数据库  
  59. - (void)connect  
  60. {  
  61.     if (!_dataBase) {  
  62.         _dataBase = [[FMDatabase alloc] initWithPath:_dbPath];  
  63.     }  
  64.     if (![_dataBase open]) {  
  65.         NSLog(@"不能打开数据库");  
  66.     }  
  67. }  
  68.   
  69. - (void)close  
  70. {  
  71.     [_dataBase close];  
  72.     [_sharedDBManager release];  
  73.     _sharedDBManager = nil;  
  74. }  
  75.   
  76. + (DBManager *)defaultDBManager  
  77. {  
  78.     if (!_sharedDBManager) {  
  79.         _sharedDBManager = [[DBManager alloc] init];  
  80.     }  
  81.     return _sharedDBManager;  
  82. }  
  83.   
  84.   
  85. @end  

向创建的数据库文件中添加数据表,对表的增删改查

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  UserDB.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10. #import "DBManager.h"  
  11. #import "User.h"  
  12.   
  13. @interface UserDB : NSObject{  
  14.     FMDatabase *_db;  
  15. }  
  16. //创建数据表  
  17. - (void)createTable;  
  18. //增:添加用户  
  19. - (void)updateTableWithUser:(User *)user;  
  20. //删:删除用户  
  21. - (void)deleteTableWithUserID:(NSString *)uid;  
  22. //改:修改用户信息  
  23. - (void)modifyTableWithUser:(User *)user;  
  24. //查:查找用户  
  25. - (NSArray *)queryTableWithUid:(NSString *)uid count:(int)userCount;  
  26.   
  27. @end  

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  UserDB.m  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import "UserDB.h"  
  10. #import "AppDelegate.h"  
  11.   
  12. #define kUserTableName                             @"User"  
  13.   
  14. @implementation UserDB  
  15.   
  16. - (id)init  
  17. {  
  18.     self = [super init];  
  19.     if (self) {  
  20.         //首先查看有没有数据库文件,没有就创建  
  21.         _db = [DBManager defaultDBManager].dataBase;  
  22.     }  
  23.     return self;  
  24. }  
  25.   
  26. //创建数据表  
  27. - (void)createTable  
  28. {  
  29.     FMResultSet *set = [_db executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type = 'table' and name = '%@'", kUserTableName]];  
  30.     [set next];  
  31.       
  32.     NSInteger count = [set intForColumnIndex:0];  
  33.     BOOL existTable = !!count;  
  34.     if (existTable) {  
  35.         //更新数据库  
  36.         [AppDelegate showStatusWithText:@"数据库已经存在!" duration:2];  
  37.     } else {  
  38.         //插入到数据库  
  39.         NSString *sqlStr = @"CREATE TABLE User (uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(50), description VARCHAR(100))";  
  40.         BOOL res = [_db executeUpdate:sqlStr];  
  41.         if (!res) {  
  42.             [AppDelegate showStatusWithText:@"数据库创建失败!" duration:2];  
  43.         } else {  
  44.             [AppDelegate showStatusWithText:@"数据库创建成功!" duration:2];  
  45.         }  
  46.           
  47.     }  
  48. }  
  49.   
  50. //保存数据  
  51. - (void)updateTableWithUser:(User *)user  
  52. {  
  53.     NSMutableString *query = [NSMutableString stringWithFormat:@"INSERT INTO User"];  
  54.     NSMutableString *keys = [NSMutableString stringWithFormat:@" ("];  
  55.     NSMutableString *values = [NSMutableString stringWithFormat:@" ( "];  
  56.     NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:5];  
  57.     if (user.name) {  
  58.         [keys appendString:@"name,"];  
  59.         [values appendString:@"?,"];  
  60.         [arguments addObject:user.name];  
  61.     }  
  62.     if (user.description) {  
  63.         [keys appendString:@"description,"];  
  64.         [values appendString:@"?,"];  
  65.         [arguments addObject:user.description];  
  66.     }  
  67.       
  68.     [keys appendString:@")"];  
  69.     [values appendString:@")"];  
  70.     [query appendFormat:@" %@ VALUES%@", [keys stringByReplacingOccurrencesOfString:@",)" withString:@")"], [values stringByReplacingOccurrencesOfString:@",)" withString:@")"]];  
  71.     NSLog(@"插入一条语句:%@", query);  
  72.     [AppDelegate showStatusWithText:@"插入一条数据!" duration:2];  
  73.     [_db executeUpdate:query withArgumentsInArray:arguments];  
  74.       
  75. }  
  76.   
  77. //删除用户信息  
  78. - (void)deleteTableWithUserID:(NSString *)uid  
  79. {  
  80.     NSString *query = [NSString stringWithFormat:@"DELETE FROM User WHERE uid = '%@'", uid];  
  81.     [AppDelegate showStatusWithText:@"删除一条数据!" duration:2];  
  82.     [_db executeUpdate:query];  
  83. }  
  84.   
  85. //修改用户信息  
  86. - (void)modifyTableWithUser:(User *)user  
  87. {  
  88.     if (!user.uid) {  
  89.         return;  
  90.     }  
  91.     NSString *query = @"UPDATE User SET";  
  92.     NSMutableString *temp = [NSMutableString stringWithCapacity:0];  
  93.     if (user.name) {  
  94.         [temp appendFormat:@"name = '%@',", user.name];  
  95.     }  
  96.     if (user.description) {  
  97.         [temp appendFormat:@"description = '%@',", user.description];  
  98.         [temp appendFormat:@")"];  
  99.         query = [query stringByAppendingFormat:@"%@ WHERE uid = '%@'", [temp stringByReplacingOccurrencesOfString:@",)" withString:@""], user.uid];  
  100.         NSLog(@"修改一条数据:%@", query);  
  101.         [AppDelegate showStatusWithText:@"修改了一条数据!" duration:2];  
  102.         [_db executeUpdate:query];  
  103.     }  
  104. }  
  105.   
  106. //查找用户  
  107. - (NSArray *)queryTableWithUid:(NSString *)uid count:(int)userCount  
  108. {  
  109.     NSString *query = @"SELECT uid, name, description FROM User";  
  110.     if (!uid) {  
  111.         query = [query stringByAppendingFormat:@" ORDER BY uid DESC limit %d", userCount];  
  112.     } else {  
  113.         query = [query stringByAppendingFormat:@" WHERE uid > %@ ORDER BY uid DESC limit %d", uid, userCount];  
  114.     }  
  115.     NSLog(@"query = %@", query);  
  116.     FMResultSet *rs = [_db executeQuery:query];  
  117.     NSMutableArray *array = [NSMutableArray arrayWithCapacity:[rs columnCount]];  
  118.     while ([rs next]) {  
  119.         User *user = [[User alloc] init];  
  120.         user.uid = [rs stringForColumn:@"uid"];  
  121.         user.name = [rs stringForColumn:@"name"];  
  122.         user.description = [rs stringForColumn:@"description"];  
  123.         NSLog(@"user.uid = %@\nuser.name = %@\nuser.des = %@\n", user.uid, user.name, user.description);  
  124.         [array addObject:user];  
  125.         [user release];  
  126.     }  
  127.     [rs close];  
  128.     NSLog(@"array = %@\n", array);  
  129.     return array;  
  130. }  
  131.   
  132.   
  133. @end  

数据模型类

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  User.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. @interface User : NSObject  
  12.   
  13. @property (copynonatomicNSString *uid;  
  14. @property (copynonatomicNSString *name;  
  15. @property (copynonatomicNSString *description;  
  16.   
  17. @end  

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  User.m  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8.   
  9. #import "User.h"  
  10.   
  11. @implementation User  
  12.   
  13. @synthesize uid, name, description;  
  14.   
  15. @end  


关于数据库的操作在上面代码中基本都包含,你也可以点击下载SQLite3Demo源码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值