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

来源:互联网 发布:网络设备监控软件 开源 编辑:程序博客网 时间:2024/05/18 02:38

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.

1 0
原创粉丝点击