码迷,mamicode.com
首页 > 数据库 > 详细

FMDB的使用

时间:2015-04-01 00:26:44      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:

安装

fmdb的官方源代码github地址是https://github.com/ccgus/fmdb。github上基本每一个第三方工具都会有大概介绍它的使用方法,而这个fmdb也不例外。它的安装可以使用CocoaPods,在podfile中加入这个

pod ‘FMDB‘
# pod ‘FMDB/SQLCipher‘

进行安装。其实你也可以下载它的压缩包下来,解压后将fmdb文件夹放到你的工程文件中,然后选择Copy items into destination group’s folder(if needed)进行手动安装,然后加入libsqlite3.0.dylib这个框架。然后你就可以使用这个fmdb了。

fmdb的使用

正如官方说明的那样下面的三个类是fmdb中用的最多的:

FMDatabase:代表了轻量的SQLite数据库,执行数据库的那些语句去使用这个类。
FMDatabaseQueue:如果你想在多线程中使用查询和更新操作,你会用到这个类。
和FMResultSet:代表了在FMDatabase中执行一个查询操作的结果。

1.FMDB的创建:

一般是在特定的路径下创建FMDB。通常放在document文件夹下面。通过[FMDatabase databaseWithPath:]来创建。

#define dataBasePath [[(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)) lastObject]stringByAppendingPathComponent:dataBaseName]
#define dataBaseName @"sanjunsheng.sqlite"

FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];

FMDB的打开:

if (![db open]) {
    NSlog(@:"Could not open db")
    return;
}

2.FMDB操作总览:

UPDATE操作:在FMDB中除了SELECT这样的语句其他的都用的是带update的执行方法:它包括
CREATE,UPDATE,INSERT,ALTER,COMMIT,BEGIN,DETACH,END,EXPLAIN,VACUUM和REPLACE等,基本上如果不是以SELECT开头的都是用update.执行update返回一个简单的BOOL的数值。如果是YES那么表明update 成功了。Query操作:这个操作返回查询后的一个FMResultSet的结果FMResultSet s= [db executeQuery:@”select from user”]; while ([s next]) { }这样你就能得到查询结果中的每一个值。用[s next]可以轮询query回来的资料,每一次的next可以得到一个row裡对应的数值,并用

intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dateForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumnName:
objectForColumnName:

这些方法把值转成Object-C的型态,然后再关闭.[db close];

3.创建表:

首先先要判断这个表是否存在,FMDB提供了相应的方法tableExists,很简便。因此我们可以这样很简便地创建表(最新的api中好像已经不存在:):
判断某个table是否存在:

//根据表的名字判断表是否存在
- (BOOL)isTableExistWithTableName:(NSString *)tableName
{
    if (![db open]) {
        return NO;
    }
    FMResultSet *set = [db executeQuery:@"select count(*) as count from sqlite_master where type = ‘table‘ and name = ?",tableName];
    if ([set next]) {
        NSInteger count = [set intForColumn:@"count"];
        if (0 == count) {
            return NO;
        }
        return YES;
    }
    return NO;
}
NSString *const studentTable = @"studentTable";
 NSString *const studentName = @"studentName";
 NSString *const studentClass = @"studentClass";
NSString *const studentAddress = @"studentAddress";
NSString *const studentAge = @"studentAge";
NSString * const studentScore = @"studentScore";
 - (BOOL)createStudentTable
{
    BOOL state = NO;
    if (![db open]) {
        return NO;
    }
    if (![self isTableExistWithTableName:studentTable]) {
        NSString *sqlString = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ TEXT PRIMARY KEY, %@ TEXT DEAFAULT ‘‘, %@ INTEGER DEFAULT 0, %@ INTEGER DEFAULT 0,%@ INTEGER DEFAULT 0,)",studentTable,studentName,studentClass,studentAddress,studentAge,studentScore];
        state = [shareDataBase executeUpdate:sqlStr];
    }
    [db close];
    return state;
}

4.向表中插入数据:

有两种插入的语句:
第一种是指定列的:

insert into table_name values (:v1,:v2,:v3)
等价于:
insert into table_name values (?:?:?)

例如往user这个表中插入:

[db executeUpdate:@"insert into user (title,originalPrice,salePrice,kindOfItem,imgUrl,goodsUrl,merchantName) values(?,?,?,?,?,?,?)",item.title,[NSNumber numberWithInt:[item.originalPrice integerValue]] ,[NSNumber numberWithInt:[item.salePrice integerValue]],item.kindOfItem,item.imgUrl,item.goodsUrl,item.merchantName,nil];

第二种是不指定对应的行列的,它可以根据字典的键值进行匹配插入(这种对于参数不确定或者参数数目非常大得情况就很好用):

- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments ;
- (void)saveStudentData
{
    BOOL state = NO;
   NSString *sqlStr = [NSString stringWithFormat:@"INSERT INTO %@                          VALUES                         (:%@, :%@, :%@,                :%@, :%@)"
 ,studentTable,studentName
 ,studentClass,studentAddress
 ,studentAge,studentScore];
  state = [db executeUpdate:sqlStr withParameterDictionary:studentDic];//这里studentDic是一个student对象的一个字典
    return state;
}

sql语句中可以使用\进行换行,更清晰明了.

5.查询数据:

- (NSInteger)selectScoreByStudentName:(NSString *)name
{
    NSInteger score;
    if ([shareDataBase open]) {
        NSString *sql = [NSString stringWithFormat:@"SELECT %@ FROM %@ WHERE %@ = ‘%@‘",studentScore,studentTable,studentName,student.name];
        FMResultSet *resultSet = [shareDataBase executeQuery:sql];
        while ([resultSet next]) {
            score = [resultSet intForColumn:@"studentScore"];
        }
        [shareDataBase close];
    }
    return score;
}

6.更新表中的数据:

- (BOOL)updateStudentInfomationByName:(NSString *)name withSudentDictionay:(studentModel *)studentModel
{
    BOOL state = NO;
    if ([shareDataBase open]) {
        NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ‘%@‘ ,%@ = ‘%@‘ , %@ = ‘%@‘ ,%@ = ‘%@‘ WHERE %@ = ‘%@‘",
                         studentTable,
                         studentClass,studentModel.studentAddress,
                         studentAge,studentModel.studentAge,
                         studentScore,studentModel.studentScore,
                         studentName,studentModel.studentName];
        state = [shareDataBase executeUpdate:sql];
        [shareDataBase close];
    }

    return state;
}

7.清空表中的数据:

+ (void)clearTableData
{
    if ([[FmdbManager sharedInstance] executeUpdate:@"DELETE FROM user"]) {       
    }else{
        NSLog(@"fail to clear");
    }
}

8.FMDatabaseQueue和线程安全:

首先创建队列:

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dataBasePath]

使用:

[queue inDatabase:^(FMDatabase *db) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];

    FMResultSet *rs = [db executeQuery:@"select * from foo"];
    while ([rs next]) {
        …
    }
}];

9.处理事务:

[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];

    if (whoopsSomethingWrongHappened) {
        *rollback = YES;
        return;
    }
    // etc…
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
}];

10.一些有用的sql语句概述:

NSString *sqlStr = [NSString stringWithFormat:@"SELECT SUM(%@) FROM %@ ", subjectScore, studentTable];
//读取所有的科目分数总和,
NSString *sqlStr = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE %@=‘%@‘ OR %@=‘%@‘", merchantTable, merchantName, good.name, merchantId, good.id];
//查询所有的符合这两个条件之一的商品的数目

配合这个使用即可查的数量:

int count;
  FMResultSet *result = [db executeQuery:sqlStr];
  while ([result next])
   {
      int count = [result intForColumnIndex:0];
    }
return count;

若有错误,希望指出。如想转载,请注明出处,谢谢。

FMDB的使用

标签:

原文地址:http://blog.csdn.net/sanjunsheng/article/details/44787997

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!