iOS开发——数据库(FMDB框架的使用)

FMDB是iOS开发中常用的sqlite数据库框架,它比苹果自带的Core Data框架,更加轻量级和灵活,下面就介绍下框架的基本使用方法。
FMDB有三个主要类:

  • FMDatabase
  • FMResultSet
  • FMDatabaseQueue

一个FMDatabase对象就是一个sqlite数据库对象,FMDatabase用来执行sql语句的,使用FMDatabase执行查询后的结果集,FMDatabaseQueue用于在多线程中执行多个查询或更新。
下面代码实现在沙盒里创建数据库

//获取沙盒路径
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePath stringByAppendingPathComponent:@"User.sqlite"];
//创建FMDatabase对象   
FMDatabase *db = [FMDatabase databaseWithPath:filePath];
//打开数据库   
if ([db open]){
    NSLog(@"Successful");
}
else{
    NSLog(@"Fail");
}
//关闭数据库
[db close];    

使用executeUpdate:方法执行更新(在FMDB中,除查询以外的所有操作,都称为更新)

//创建一个基本信息表(会员的基本信息,包括姓名、性别、年龄、工作单位、联系方式)
[db executeUpdate:@"create table if not exists t_basemessage (name text primary key ,sex text,age integer,work text,tele text)"];

//执行插入操作(这里注意不能用%@要用?)
[db executeUpdate:@"insert into t_basemessage (name,sex,age,work,tele) values(?,?,?,?,?)",self.nameText.text,self.sexText.text,self.ageText.text,self.workText.text,self.teleText.text];

//执行删除操作
[db executeUpdate:@"delete from t_basemessage where name = ?",self.nameText.text];

执行查询操作

//查询方法
- (FMResultSet *)executeQuery:(NSString*)sql, ...
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments

代码示例:

// 查询数据
FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"];

// 遍历结果集
while ([rs next]) {
    NSString *name = [rs stringForColumn:@"name"];
    int age = [rs intForColumn:@"age"];
    double score = [rs doubleForColumn:@"score"];
}

FMDatabase这个类是线程不安全的,如果在多个线程中同时使用一个FMDatabase实例,会造成数据混乱等问题
为了保证线程安全,FMDB提供方便快捷的FMDatabaseQueue类

//FMDatabaseQueue的创建
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];

以上就是FMDB的基本使用方法和例子,其中有些代码是我数据库课程设计中的代码,如果需要课程设计源码的可以联系我,邮箱ahtchxw@qq.com.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值