大家工作中,最常用到的无非是 增、删、查、改。。。
在SQL中对应的语句为:INSERT DELETE SELECT UPDATE
首先,你可以使用一款叫做“sqlite database browser”的工具来可视化的管理。
然后把数据库文件加入到Resource目录下,然后通过以下代码来安装数据库,也就是拷贝到doc目录下:
- //install file to doc dir
- - (BOOL)installFileOfName:(NSString *)fileName {
- NSString *pathForDoc = nil;
- NSString *pathForRes = nil;
- pathForDoc = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];
- //NSLog(@"%@",pathForDoc);
- if ([[NSFileManager defaultManager] fileExistsAtPath:pathForDoc] == YES) {
- return NO;
- }else {
- pathForRes = [[NSBundle mainBundle] pathForResource:fileName ofType:[fileName pathExtension]];
- NSData *fileData = [NSData dataWithContentsOfFile:pathForRes];
- [[NSFileManager defaultManager] createFileAtPath:pathForDoc contents:fileData attributes:nil];
- return YES;
- }
- }
上面这个方法,你可以直接调用,传递一个数据库文件名,然后它会把它复制到doc目录。
下面是一些FMDB的操作,安装、打开数据库:
- if ([self installFileOfName:@"test_db"] == YES) {
- NSLog(@"install database success.");
- }else {
- NSLog(@"install database fail.");
- }
- NSString *dbPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",@"test_db"];
- //NSLog(@"database path:%@",dbPath);
- FMDatabase *fm = [FMDatabase databaseWithPath:dbPath];
- if ([fm open] == YES) {
- NSLog(@"open database success.");
- }else {
- NSLog(@"open database fail.");
- return;
- }
向数据库插入一条记录:
- BOOL operaResult = [fm executeUpdate:@"INSERT INTO test_tab (name,age,mail) VALUES (?,?,?)",@"佳",@"4",@"c0066@gmail.com"];
修改数据库中的某条记录:
- BOOL operaResult = [fm executeUpdate:@"UPDATE test_tab SET name=? WHERE name=?",@"123",@"佳"];
从数据库删除某条记录:
- BOOL operaResult = [fm executeUpdate:@"DELETE FROM test_tab WHERE name=?",@"jiajia"];
从数据库获得记录,并按照降序排序:
-
- FMResultSet *s = [fm executeQuery:@"SELECT * FROM test_tab ORDER BY age DESC"];