天天看点

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文件。

iOS 数据持久化四-SQLite3

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

iOS 数据持久化四-SQLite3
iOS 数据持久化四-SQLite3
  1. //  
  2. //  AppDelegate.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-22.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8. #import <UIKit/UIKit.h>  
  9. @interface AppDelegate : UIResponder <UIApplicationDelegate>  
  10. @property (strong, nonatomic) UIWindow *window;  
  11. + (void)showStatusWithText:(NSString *)string duration:(NSTimeInterval)duration;  
  12. @end  

AppDelegate.m文件

[objc]  view plain copy

iOS 数据持久化四-SQLite3
iOS 数据持久化四-SQLite3
  1. //  
  2. //  AppDelegate.m  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-22.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8. #import "AppDelegate.h"  
  9. #import "RootViewController.h"  
  10. @interface AppDelegate ()  
  11. @property (strong, nonatomic) UIWindow *statusWindow;  
  12. @property (retain, nonatomic) UILabel *statusLabel;  
  13. - (void)dismissStatusLabel;  
  14. @end  
  15. @implementation AppDelegate  
  16. - (void)dealloc  
  17. {  
  18.     [self.statusWindow release];  
  19.     [self.statusLabel release];  
  20.     [_window release];  
  21.     [super dealloc];  
  22. }  
  23. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  24. {  
  25.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  26.     self.statusWindow = [[UIWindow alloc] initWithFrame:CGRectZero];  
  27.     self.statusWindow.backgroundColor = [UIColor clearColor];  
  28.     self.statusWindow.windowLevel = UIWindowLevelStatusBar + 1;  
  29.     self.statusLabel = [[UILabel alloc] initWithFrame:CGRectZero];  
  30.     self.statusLabel.backgroundColor = [UIColor clearColor];  
  31.     self.statusLabel.textColor = [UIColor whiteColor];  
  32.     self.statusLabel.font = [UIFont systemFontOfSize:13];  
  33.     [self.statusWindow addSubview:self.statusLabel];  
  34.     [self.statusWindow makeKeyAndVisible];  
  35.     RootViewController *rootVC = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];  
  36.     UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:rootVC];  
  37.     [rootVC release];  
  38.     self.window.rootViewController = rootNav;  
  39.     [rootNav release];  
  40.     // Override point for customization after application launch.  
  41.     self.window.backgroundColor = [UIColor whiteColor];  
  42.     [self.window makeKeyAndVisible];  
  43.     return YES;  
  44. }  
  45. #pragma mark - Custom methods  
  46. - (void)dismissStatusLabel  
  47. {  
  48.     CGRect rect = self.statusWindow.frame;  
  49.     rect.origin.y -= rect.size.height;  
  50.     [UIView animateWithDuration:0.8 animations:^{  
  51.         self.statusWindow.frame = rect;  
  52.     }];  
  53. }  
  54. + (void)showStatusWithText:(NSString *)string duration:(NSTimeInterval)duration  
  55. {  
  56.     AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;  
  57.     delegate.statusLabel.text = string;  
  58.     [delegate.statusLabel sizeToFit];  
  59.     CGRect rect = [UIApplication sharedApplication].statusBarFrame;  
  60.     CGFloat width = delegate.statusLabel.frame.size.width;  
  61.     CGFloat height = rect.size.height;  
  62.     rect.origin.x = rect.size.width = width - 5;  
  63.     rect.size.width = width;  
  64.     delegate.statusWindow.frame = rect;  
  65.     delegate.statusLabel.backgroundColor = [UIColor blackColor];  
  66.     delegate.statusLabel.frame = CGRectMake(100, 0, width, height);  
  67.     duration = (duration < 1.0 ? 1.0 : duration);  
  68.     duration = (duration > 4.0 ? 4.0 : duration);  
  69.     [delegate performSelector:@selector(dismissStatusLabel)];  
  70. }  
  71. @end  

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

[objc]  view plain copy

iOS 数据持久化四-SQLite3
iOS 数据持久化四-SQLite3
  1. //  
  2. //  DBManager.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8. #import <Foundation/Foundation.h>  
  9. #import "FMDatabaseAdditions.h"  
  10. @class FMDatabase;  
  11. @interface DBManager : NSObject{  
  12.     NSString *_dbPath;  
  13. }  
  14. @property (readonly, nonatomic) FMDatabase *dataBase;  
  15. //单例模式  
  16. + (DBManager *)defaultDBManager;  
  17. //关闭数据库  
  18. - (void)close;  
  19. @end  

[objc]  view plain copy

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

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

[objc]  view plain copy

iOS 数据持久化四-SQLite3
iOS 数据持久化四-SQLite3
  1. //  
  2. //  UserDB.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8. #import <Foundation/Foundation.h>  
  9. #import "DBManager.h"  
  10. #import "User.h"  
  11. @interface UserDB : NSObject{  
  12.     FMDatabase *_db;  
  13. }  
  14. //创建数据表  
  15. - (void)createTable;  
  16. //增:添加用户  
  17. - (void)updateTableWithUser:(User *)user;  
  18. //删:删除用户  
  19. - (void)deleteTableWithUserID:(NSString *)uid;  
  20. //改:修改用户信息  
  21. - (void)modifyTableWithUser:(User *)user;  
  22. //查:查找用户  
  23. - (NSArray *)queryTableWithUid:(NSString *)uid count:(int)userCount;  
  24. @end  

[objc]  view plain copy

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

数据模型类

[objc]  view plain copy

iOS 数据持久化四-SQLite3
iOS 数据持久化四-SQLite3
  1. //  
  2. //  User.h  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8. #import <Foundation/Foundation.h>  
  9. @interface User : NSObject  
  10. @property (copy, nonatomic) NSString *uid;  
  11. @property (copy, nonatomic) NSString *name;  
  12. @property (copy, nonatomic) NSString *description;  
  13. @end  

[objc]  view plain copy

iOS 数据持久化四-SQLite3
iOS 数据持久化四-SQLite3
  1. //  
  2. //  User.m  
  3. //  SQLite3Demo  
  4. //  
  5. //  Created by 李振杰 on 13-11-26.  
  6. //  Copyright (c) 2013年 swplzj. All rights reserved.  
  7. //  
  8. #import "User.h"  
  9. @implementation User  
  10. @synthesize uid, name, description;  
  11. @end  

关于数据库的操作在上面代码中基本都包含,你也可以点击下载SQLite3Demo源码。