SQLite是一种小型的轻量级的关系型数据库,在移动设备上使用是非常好的选择,无论是Android还是iOS,都内置了SQLite数据库,现在的版本都是SQLite3。在IOS中使用SQLite如果使用SDK提供的方法,特别麻烦也不利于理解和使用,在之前的http://blog.csdn.net/tangren03/article/details/7781930文章中就是使用IOS的SDK自带的SQLite API来使用数据库,感觉使用很不方便,今天就讲讲一个针对IOS的SQlite API封装的第三方库FMDB,FMDB对SDK中的API做了一层封装,使之使用OC来访问,使用方便而且更熟悉。FMDB的下载地址https://github.com/ccgus/fmdb。
IOS学习笔记28
FMDB主要涉及两个类,FMDatabase和FMResultSet,前者类似于Android中的SQLiteOpenHelper或SQLiteDatabase,FMResultSet类似于Android中的Cursor,用来存储结果集。
下载完FMDB源码后把文件拖到工程中,并导入SQLite支持库,工程目录如下:
然后就是这个Demo的完整截图:
然后就来看看如何操作FMDB:
[cpp]view plaincopy
//点击按钮后执行保存到数据库的操作
- (IBAction)saveButtonClicked:(id)sender {
//获取Document文件夹下的数据库文件,没有则创建
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
//获取数据库并打开
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
if(![database open]) {
NSLog(@"Open database failed");
return;
}
//创建表(FMDB中只有update和query操作,出了查询其他都是update操作)
[database executeUpdate:@"create table user (name text,gender text,age integer)"];
//插入数据
BOOLinsert = [database executeUpdate:@"insert into user values (?,?,?)",nameTextField.text,genderTextField.text,ageTextField.text];
if(insert) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"message:@"保存成功"delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
[database close];
}
操作成功后弹出提示框:
[cpp]view plaincopy
//点击按钮后执行查询操作
- (IBAction)queryButtonTapped:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *dbPath = [documentPath stringByAppendingPathComponent:@"user.db"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
if(![database open]) {
return;
}
//不需要像Android中那样关闭Cursor关闭FMResultSet,因为相关的数据库关闭时,FMResultSet也会被自动关闭
FMResultSet *resultSet = [database executeQuery:@"select * from user"];
while([resultSet next]) {
NSString *name = [resultSet stringForColumn:@"name"];
NSString *gender = [resultSet stringForColumn:@"gender"];
intage = [resultSet intForColumn:@"age"];
NSLog(@"Name:%@,Gender:%@,Age:%d",name,gender,age);
}
[database close];
//这里也不需要release
// [database release];
}
FMResultSet还支持以下方式获取值:
intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dateForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumnIndex:
objectForColumn:
[cpp]view plaincopy
//执行条件查询操作
- (IBAction)queryByConditionBtnTapped:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex:0];
NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
if(![database open]) {
return;
}
FMResultSet *resultSet = [database executeQuery:@"select * from user where name = ?",@"Ryan"];
while([resultSet next]) {
NSString *name = [resultSet stringForColumn:@"name"];
NSString *gender = [resultSet stringForColumn:@"gender"];
intage = [resultSet intForColumn:@"age"];
NSLog(@"Name:%@,Gender:%@,Age:%d",name,gender,age);
}
[database close];
}
[cpp]view plaincopy
//执行更新操作
- (IBAction)updateBtnTapped:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex:0];
NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
if(![database open]) {
return;
}
//参数必须是NSObject的子类,int,double,bool这种基本类型,需要封装成对应的包装类才可以
BOOLupdate = [database executeUpdate:@"update user set name = ? where age = ?",@"RyanTang",[NSNumber numberWithInt:24]];
if(update){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"message:@"更新成功"delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
[database close];
}
[cpp]view plaincopy
//执行删除操作
- (IBAction)deleteBtnTapped:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex:0];
NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
if(![database open]) {
return;
}
BOOLdelete= [database executeUpdate:@"delete from user where name = ?",@"Tang"];
if(delete) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"message:@"删除成功"delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
[database close];
}
如果我们的app需要多线程操作数据库,那么就需要使用FMDatabaseQueue来保证线程安全了。切记不能在多个线程中共同一个FMDatabase对象并且在多个线程中同时使用,这个类本身不是线程安全的,这样使用会造成数据混乱等问题。
使用FMDatabaseQueue很简单,首先用一个数据库文件地址来初使化FMDatabaseQueue,然后就可以将一个闭包(block)传入inDatabase方法中。在闭包中操作数据库,而不直接参与FMDatabase的管理。
[cpp]view plaincopy
-(void)executeDBOperation
{
//获取Document文件夹下的数据库文件,没有则创建
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"];
FMDatabaseQueue *databaseQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
[databaseQueue inDatabase:^(FMDatabase *db){
[db executeUpdate:@"insert into user values (?,?,?)",@"Ren",@"Male",[NSNumber numberWithInt:20]];
}];
[databaseQueue close];
}
工程源码:下载
加入我们的QQ群或微信公众账号请查看:Ryan's zone公众账号及QQ群
欢迎关注我的新浪微博和我交流:@唐韧_Ryan
顶
12
踩