创建,插入,更新和删除:使用executeUpdate方法,而查询则用executeQuery
1.实例化FMDatabase
//paths: ios下Document路径,Document为ios中可读写的文件夹
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
//dbPath: 数据库路径,在Document中。
NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"Test.db"];
//创建数据库实例 db 这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
FMDatabase *db= [FMDatabase databaseWithPath:dbPath] ;
if (![db open]) {
NSLog(@"Could not open db.");
return ;
}
2.创建表
//创建一个名为User的表,有两个字段分别为string类型的Name,integer类型的 Age
[db executeUpdate:@"CREATE TABLE User (Name text,Age integer)"];
3.插入
//插入数据使用OC中的类型 text对应为NSString integer对应为NSNumber的整形
[db executeUpdate:@"INSERT INTO User (Name,Age) VALUES (?,?)",@"张三",[NSNumber numberWithInt:20]];
4.更新
//更新数据 将“张三”更改为“李四”
[db executeUpdate:@"UPDATE User SET Name = ? WHERE Name = ? ",@"李四",@"张三"];
5.删除
//删除数据
[db executeUpdate:@"DELETE FROM User WHERE Name = ?",@"张三"];
6.查询
//返回数据库中第一条满足条件的结果
NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
//返回全部查询结果
FMResultSet *rs=[db executeQuery:@"SELECT * FROM User"];
rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
while ([rs next]){
NSLog(@"%@ %@",[rs stringForColumn:@"Name"],[rs stringForColumn:@"Age"]);
}
[rs close];