iOS开发-数据篇-sqlite存储
简介:iOS开发的持久化数据存储有4种方式:NSUserDefault和.plist、NSKeyedArchiver和NSKeyedUnarchiver、sqlite3数据库、CoreData。
sqlite3和CoreData适合存储大量数据(内容数据等),而另外两种适合存储简单数据(语言,字体,标记等简单数据存储)。
准备:这里主要介绍利用sqlite3封装的FMDatabase的数据库,(当然还有PlausibleDatabase、sqlitepersistentobjects等其他封装的库),导入需要依赖的libsqlite3.dylib包,FMDatabase已经根据工程不同情况兼容ARC和非ARC。为了只针对数据库进行讲解,直接创建一个简单工程,导入FMDatabase库。
内容:1.创建数据库
#import <UIKit/UIKit.h> #import "FMDatabase.h" #import "FMDatabaseQueue.h" @interface ViewController : UIViewController{ FMDatabase *db; FMDatabaseQueue *queue_db; }
//创建数据库文件路径 - (NSString*)getPath{ NSArray* paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) ; return [[paths objectAtIndex:0]stringByAppendingPathComponent:@"TEST.sqlite"] ; }
2.数据库的建表-增-删-改操作
- (void)viewDidLoad { [super viewDidLoad]; [self executeSql:[self createTable]];//创表 [self executeSql:[self insertData]];//增 [self executeSql:[self deleteData]];//删 [self executeSql:[self setData]];//改 //查 [self queryData]; //开辟多线程 [NSThread detachNewThreadSelector:@selector(multipleThread) toTarget:self withObject:nil]; }
//创建数据库 -(NSString *)createTable{ NSString *createSql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS TEST(a interger,b text)"]; return createSql; } //增 - (NSString *)insertData{ NSString *insertSql= [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@') VALUES ('%@', '%@')", @"TEST", @"a", @"b", [NSNumber numberWithInt:1], @"宁波"]; return insertSql; } //删 - (NSString *)deleteData{ NSString *deleteSql = [NSString stringWithFormat: @"DELETE FROM '%@' where %@ = '%@'", @"TEST", @"b", @"宁波"]; return deleteSql; } //改 -(NSString *)setData{ NSString *setSql = [NSString stringWithFormat:@"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'", @"TEST", @"b", @"象山" ,@"a", [NSNumber numberWithInt:1]]; return setSql; }
3.数据库的执行操作
//数据库执行操作 -(BOOL)executeSql:(NSString *)sql{ db = [FMDatabase databaseWithPath:[self getPath]]; BOOL success; if ([db open]) { success = [db executeUpdate:sql]; }else{ NSLog(@"OPEN FAIL"); } [db close]; return success; }
4.数据库的查询操作
//查 -(void)queryData{ if ([db open]) { NSString *querySql = [NSString stringWithFormat: @"SELECT * FROM %@",@"TEST"]; FMResultSet * rs = [db executeQuery:querySql]; while ([rs next]) { int a = [rs intForColumn:@"a"]; NSString *b = [rs stringForColumn:@"b"]; NSLog(@"a:%d == b:%@",a,b); } [db close]; } }
5.数据库的多线程操作
若在多线程的环境下,不能在多线程中共用同一个FMDatabase进行数据访问,会造成数据混乱,多线程下不能用单例对象,这时得依靠FMDatabaseQueue。
//多线程下使用FMDatabaseQueue进行数据库操作 -(void)multipleThread{ queue_db = [FMDatabaseQueue databaseQueueWithPath:[self getPath]]; @autoreleasepool{ [queue_db inDatabase:^(FMDatabase *db2) { [db2 executeUpdate:[self insertData]]; [self queryData]; }]; } }