FMDB总结
打开数据库
根据path打开数据库
// 1..创建数据库对象
FMDatabase *db = [FMDatabase databaseWithPath:path];
// 2.打开数据库
if ([db open]) {
// do something
}
else {
NSLog(@"fail to open database");
}
文件路径有三种
路径不存在
会自动创建
空字符串 @""
会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,数据库文件也被删除
nil
会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁
数据库操作
查询
查询方法
(FMResultSet )executeQuery:(NSString)sql
(FMResultSet )executeQueryWithFormat:(NSString)format
// 4.查询
NSString *sql = @"select id, name, age FROM t_student";
FMResultSet *rs = [db executeQuery:sql];
while ([rs next]) {
int id = [rs intForColumnIndex:0];
NSString *name = [rs stringForColumnIndex:1];
int age = [rs intForColumnIndex:2];
Student *student = [[Student alloc] init];
student.name = name;
student.age = age;
[students addObject:student];
}
更新
在FMDB中,除查询以外的所有操作,都称为“更新”
- create
- drop
- insert
- update
- delete
使用executeUpdate:
执行更新
创建表
NSString *createTableSqlString = @"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL)";
[db executeUpdate:createTableSqlString];
写入数据
NSString *sql = @"insert into t_student (name, age) values (?, ?)";
NSString *name = [NSString stringWithFormat:@"Jack - %d",arc4random()];
NSNumber *age = [NSNumber numberWithInt:arc4random_uniform(100)];
[db executeUpdate:sql, name, age];
删除数据
// 删除数据
NSString *sql = @"delete from t_student where id = ?";
[db executeUpdate:sql, [NSNumber numberWithInt:1]];
更改数据
// 更改数据
NSString *sql = @"update t_student set name = 'Tom' where id = ?";
[db executeUpdate:sql, [NSNumber numberWithInt:2]];
使用executeUpdateWithFormat:
执行更新
// 使用executeUpdateWithFormat: - 不确定的参数用%@,%d等来占位
NSString *sql = @"insert into t_student (name,age) values (%@,%i)";
NSString *name = [NSString stringWithFormat:@"孙悟空 - %d",arc4random()];
[db executeUpdateWithFormat:sql, name, arc4random_uniform(100)];
使用 executeUpdate:withParameterDictionary:
执行更新
// 使用 executeUpdate:withParameterDictionary:
NSString *name = [NSString stringWithFormat:@"玉皇大帝 - %d",arc4random()];
NSNumber *age = [NSNumber numberWithInt:arc4random_uniform(100)];
NSDictionary *studentDict = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", age, @"age", nil];
[db executeUpdate:@"insert into t_student (name, age) values (:name, :age)" withParameterDictionary:studentDict];