转载地址:http://www.cnblogs.com/wendingding/p/3871848.html
如果想了解SQLite,地址:http://blog.csdn.net/qq_27325349/article/details/50281501
/* FMDB是iOS平台的SQLite数据库框架 FMDB有三个主要的类 (1)FMDatabase:一个FMDatabase对象就代表一个单独的SQLite数据库,用来执行SQL语句。 (2)FMResultSet:使用FMDatabase执行查询后的结果集。 (3)FMDatabaseQueue:用于在多线程中执行多个查询或者更新,它是线程安全的。 ===》在FMDB中,除查询以外的所有操作,都称为“更新”。 ===》注意要导入libsqlite3库。 ===》FMDB的优点: (1)使用起来更加面向对象,省去了很多麻烦,冗余的C语言代码 (2)对比苹果自带的Core Data框架,更加轻量级 (3)提供了多线程安全的数据库操作,有效防治数据混乱 */ #import "ViewController.h" #import "FMDB.h" @interface ViewController () @property(nonatomic,strong)FMDatabase *db; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self createTable]; // [self insertDataWithName:@"zhangsan" andHeight:@"173"]; // [self insertDataWithName:@"lisi" andHeight:@"174"]; // [self insertDataWithName:@"wangwu" andHeight:@"175"]; // [self insertDataWithName:@"hushuting" andHeight:@"176"]; // [self insertDataWithName:@"gujinyue" andHeight:@"177"]; [self queryData]; // [self deleteDataWithName:@"lisi"]; // [self queryData]; [self updateDateByName:@"gujinyue" andWithHeight:@"178"]; [self queryData]; } /** * 创建表 */ -(void)createTable { //1.获取数据库文件的路径 NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *fileName=[doc stringByAppendingPathComponent:@"gujinyue.sqlite"]; NSLog(@"%@",fileName); //2.获得数据库 FMDatabase *db=[FMDatabase databaseWithPath:fileName]; //3.打开数据库 if ([db open]) { //4.创建表(三个属性:ID,姓名,身高) // NSString *sqlCreate=@"create table if not exists table_student(id NSString,name NSString,height NSString)"; NSString *sqlCreate=@"create table if not exists table_student (id integer PRIMARY KEY AUTOINCREMENT, name NSString, height NSString)"; BOOL result=[db executeUpdate:sqlCreate]; if(result) { NSLog(@"创建表成功"); } else { NSLog(@"创建表失败"); } } self.db=db; } /** * 增加数据 * * @param name 姓名 * @param height 身高 */ -(void)insertDataWithName:(NSString *)name andHeight:(NSString *)height { [self.db executeUpdate:@"insert into table_student(name,height) values(?,?);",name,height]; } /** * 删除数据 * * @param name 姓名 */ -(void)deleteDataWithName:(NSString *)name { [self.db executeUpdate:@"delete from table_student where name=?",name]; } /** * 修改数据 * * @param name 姓名 * @param height 身高 */ -(void)updateDateByName:(NSString *)name andWithHeight:(NSString *)height { [self.db executeUpdate:@"update table_student set height=? where name=?",height,name]; } /** * 查询数据 */ -(void)queryData { //1.查询结果 FMResultSet *resultSet=[self.db executeQuery:@"select *from table_student"]; //2.遍历结果集 while ([resultSet next]) { long ID=[resultSet intForColumn:@"id"]; NSString *name=[resultSet stringForColumn:@"name"]; NSString *height=[resultSet stringForColumn:@"height"]; NSLog(@"%ld %@ %@",ID,name,height); } } @end