本文主要是介绍IOS数据持久化存储之SQLite3第三方库FMDB的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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。
FMDB主要涉及两个类,FMDatabase和FMResultSet,前者类似于Android中的SQLiteOpenHelper或SQLiteDatabase,FMResultSet类似于Android中的Cursor,用来存储结果集。
FMDB常用类:
FMDatabase : 一个单一的SQLite数据库,用于执行SQL语句。
FMResultSet :执行查询一个FMDatabase结果集,这个和android的Cursor类似。
FMDatabaseQueue :在多个线程来执行查询和更新时会使用这个类。
创建数据库:
- db = [FMDatabase databaseWithPath:database_path];
1、当数据库文件不存在时,fmdb会自己创建一个。
2、 如果你传入的参数是空串:@"" ,则fmdb会在临时文件目录下创建这个数据库,数据库断开连接时,数据库文件被删除。
3、如果你传入的参数是 NULL,则它会建立一个在内存中的数据库,数据库断开连接时,数据库文件被删除。
打开数据库:
- [db open]
关闭数据库:
- [db close]
数据库增删改等操作:
除了查询操作,FMDB数据库操作都执行executeUpdate方法,这个方法返回BOOL型。
看一下例子:
例子一
创建表:
- if ([db open]) {
- NSString *sqlCreateTable = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];
- BOOL res = [db executeUpdate:sqlCreateTable];
- if (!res) {
- NSLog(@"error when creating db table");
- } else {
- NSLog(@"success to creating db table");
- }
- [db close];
- }
添加数据:
- if ([db open]) {
- NSString *insertSql1= [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
- TABLENAME, NAME, AGE, ADDRESS, @"张三", @"13", @"济南"];
- BOOL res = [db executeUpdate:insertSql1];
- NSString *insertSql2 = [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
- TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"济南"];
- BOOL res2 = [db executeUpdate:insertSql2];
- if (!res) {
- NSLog(@"error when insert db table");
- } else {
- NSLog(@"success to insert db table");
- }
- [db close];
- }
修改数据:
- if ([db open]) {
- NSString *updateSql = [NSString stringWithFormat:
- @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",
- TABLENAME, AGE, @"15" ,AGE, @"13"];
- BOOL res = [db executeUpdate:updateSql];
- if (!res) {
- NSLog(@"error when update db table");
- } else {
- NSLog(@"success to update db table");
- }
- [db close];
- }
删除数据:
- if ([db open]) {
- NSString *deleteSql = [NSString stringWithFormat:
- @"delete from %@ where %@ = '%@'",
- TABLENAME, NAME, @"张三"];
- BOOL res = [db executeUpdate:deleteSql];
- if (!res) {
- NSLog(@"error when delete db table");
- } else {
- NSLog(@"success to delete db table");
- }
- [db close];
- }
数据库查询操作:
查询操作使用了executeQuery,并涉及到FMResultSet。
- if ([db open]) {
- NSString * sql = [NSString stringWithFormat:
- @"SELECT * FROM %@",TABLENAME];
- FMResultSet * rs = [db executeQuery:sql];
- while ([rs next]) {
- int Id = [rs intForColumn:ID];
- NSString * name = [rs stringForColumn:NAME];
- NSString * age = [rs stringForColumn:AGE];
- NSString * address = [rs stringForColumn:ADDRESS];
- NSLog(@"id = %d, name = %@, age = %@ address = %@", Id, name, age, address);
- }
- [db close];
- }
数据库多线程操作:
如果应用中使用了多线程操作数据库,那么就需要使用FMDatabaseQueue来保证线程安全了。 应用中不可在多个线程中共同使用一个FMDatabase对象操作数据库,这样会引起数据库数据混乱。 为了多线程操作数据库安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很简单,首先用一个数据库文件地址来初使化FMDatabaseQueue,然后就可以将一个闭包(block)传入inDatabase方法中。 在闭包中操作数据库,而不直接参与FMDatabase的管理。
- FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
- dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
- dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
- dispatch_async(q1, ^{
- for (int i = 0; i < 50; ++i) {
- [queue inDatabase:^(FMDatabase *db2) {
- NSString *insertSql1= [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
- TABLENAME, NAME, AGE, ADDRESS];
- NSString * name = [NSString stringWithFormat:@"jack %d", i];
- NSString * age = [NSString stringWithFormat:@"%d", 10+i];
- BOOL res = [db2 executeUpdate:insertSql1, name, age,@"济南"];
- if (!res) {
- NSLog(@"error to inster data: %@", name);
- } else {
- NSLog(@"succ to inster data: %@", name);
- }
- }];
- }
- });
- dispatch_async(q2, ^{
- for (int i = 0; i < 50; ++i) {
- [queue inDatabase:^(FMDatabase *db2) {
- NSString *insertSql2= [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
- TABLENAME, NAME, AGE, ADDRESS];
- NSString * name = [NSString stringWithFormat:@"lilei %d", i];
- NSString * age = [NSString stringWithFormat:@"%d", 10+i];
- BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"];
- if (!res) {
- NSLog(@"error to inster data: %@", name);
- } else {
- NSLog(@"succ to inster data: %@", name);
- }
- }];
- }
- });
例子二:
下载完FMDB源码后把文件拖到工程中,并导入SQLite支持库,工程目录如下:
然后就是这个Demo的完整截图:
然后就来看看如何操作FMDB:
- //点击按钮后执行保存到数据库的操作
- - (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操作)
- //2014.3.6 sfx 修改:创建表时应该先查看表是否已经存在,如果不存在再创建
-
FMResultSet *rs = [database executeQuery:@"select count(*) as 'count' from sqlite_master where type = 'table' and name = ?",@"user"];
if ([rs next])
{
NSInteger count = [rs intForColumn:@"count"];
NSLog(@"The table count: %d",count);
if (count == 1) {
NSLog(@"user table is existed.");
return;
}
NSLog(@"user table is not existed.");
[database executeUpdate:@"create table user (name text,gender text,age integer)"];
}
- //插入数据
- BOOL insert = [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];
- }
操作成功后弹出提示框:
- //点击按钮后执行查询操作
- - (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"];
- int age = [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:
- //执行条件查询操作
- - (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"];
- int age = [resultSet intForColumn:@"age"];
- NSLog(@"Name:%@,Gender:%@,Age:%d",name,gender,age);
- }
- [database close];
- }
- //执行更新操作
- - (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这种基本类型,需要封装成对应的包装类才可以
- BOOL update = [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];
- }
- //执行删除操作
- - (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;
- }
- BOOL delete = [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的管理。
- -(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];
- }
经过修改后的工程源码:传送门在此
这篇关于IOS数据持久化存储之SQLite3第三方库FMDB的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!