L result = [self.database executeUpdateWithFormat:@"insert into t_student (name, age, sax) values (%@, %i, %@);", @"xiaoming", @69, @"男"];
// 更新数据
BOOL result = [self.database executeUpdateWithFormat:@"update t_student set name = %@ where name = %@", @"xiaoming", @"小明"];
// 删除数据
BOOL result = [self.database executeUpdateWithFormat:@"delete from t_student where name = %@", @"xiaoming"];
- executeUpdate:withArgumentsInArray:数组,直接使用数组
增、删、改的代码实例:
// 增加(插入)数据
[self.database executeUpdate:@"insert into t_student(name, age, sax) values(?, ?, ?);" withArgumentsInArray:@[@"xiaoming", @12, @"男"]];
// 更新数据
[self.database executeUpdate:@"update t_student set name = ? where name = ?;" withArgumentsInArray:@[@"xiaoming", @"小明"]];
// 删除数据
[self.database executeUpdate:@"delete from t_student where name = ?;" withArgumentsInArray:@[@"xiaoming"]];
以上的方法大家可以根据自己的习惯和需求选择一种即可。
3> FMDB—查询数据
① 概述
SELECT 命令就是查询,执行查询的方法是以 -excuteQuery 开头的。
执行查询时,如果成功返回 FMResultSet 对象,错误返回 nil 。与执行更新相同,支持使用 NSError 参数。
同时,你也可以使用 -lastErrorCode 和 -lastErrorMessage 获知错误信息。
② FMResultSet
FMResultSet 提供了很多方法,来获取对应字段的信息:
intForColumn:、longForColumn:、longLongIntForColumn:、boolForColumn:、doubleForColumn:、stringForColumn:、dataForColumn:、dataNoCopyForColumn:、UTF8StringForColumnIndex:、objectForColumn:
③ 执行查询语句
查询整个表
// 查询结果使用的类FMResultSet
FMResultSet *resultSet = [self.database executeQuery:@"select * from t_student"];
根据条件查询
//根据条件查询
FMResultSet *resultSet = [self.db executeQuery:@"select * from t_student where id<?;", @14];
④ 遍历结果集合
while (resultSet.next) {
NSInteger ID = [resultSet intForColumn:@"id"];
NSString *name = [resultSet objectForColumnName:@"name"];
NSInteger age = [resultSet intForColumn:@"age"];
NSString *sax = [resultSet objectForColumnName:@"sax"];
NSLog(@"id = %ld name = %@, age = %ld, sax = %@", ID, name, age, sax);
}
4> 完整实例代码
#import "ViewController.h"
// 第一步:引入框架,引入支持的类库(libsqlite3.0.tbd)
#import <FMDB.h>
@interface ViewController ()
/// 声明数据库对象
@property (nonatomic, strong) FMDatabase *database;
/// 声明存储路径
@property (nonatomic, strong) NSString *filePath;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self createTabe];
}
#pragma mark - 创建表
- (void)createTabe
{
// 第一步:创建sql语句
NSString *createSql = @"create table if not exists t_student(id integer primary key autoincrement not null, name text not null, age integer not null, sax text not null)";
// 第二步:找到存储路径
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// NSLog(@"document = %@", documentPath);
self.filePath = [documentPath stringByAppendingPathComponent:@"student.sqlite"];
NSLog(@"filePath = %@", self.filePath);
// 第三步:使用路径初始化FMDB对象
self.database = [FMDatabase databaseWithPath:self.filePat