使用资料库的第一件事,就是建立一个资料库。要注意的是,在iOS环境下,只有document directory 是可以进行读写的。在写程式时用的那个Resource资料夹底下的东西都是read-only。因此,建立的资料库要放在document 资料夹下。方法如下:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); |
| NSString *documentDirectory = [paths objectAtIndex:0]; |
| NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyDatabase.db"]; |
| FMDatabase *db = [FMDatabase databaseWithPath:dbPath] ; |
| if (![db open]) { |
| NSLog(@“Could not open db.”); |
| return ; |
| } |
建立table
1 | [db executeUpdate:@ "CREATE TABLE PersonList (Name text, Age integer, Sex integer, Phone text, Address text, Photo blob)" ]; |
1 | [db executeUpdate:@ "INSERT INTO PersonList (Name, Age, Sex, Phone, Address, Photo) VALUES (?,?,?,?,?,?)" , |
3 | @ "Jone" , [NSNumber numberWithInt:20], [NSNumber numberWithInt:0], @“091234567”, @“Taiwan, R.O.C”, [NSData dataWithContentsOfFile: filepath]]; |
| [db executeUpdate:@ "UPDATE PersonList SET Age = ? WHERE Name = ?" ,[NSNumber numberWithInt:30],@“John”]; -取得资料 取得特定的资料,则需使用FMResultSet物件接收传回的内容:
用[rs next]可以轮询query回来的资料,每一次的next可以得到一个row裡对应的数值,并用[rs stringForColumn:]或[rs intForColumn:]等方法把值转成Object-C的型态。取用完资料后则用[rs close]把结果关闭。 -快速取得资料 在有些时候,只会query某一个row裡特定的一个数值(比方只是要找John的年龄),FMDB提供了几个比较简便的方法。这些方法定义在FMDatabaseAdditions.h,如果要使用,记得先import进来。
7 int age = [db intForQuery:@"SELECT Age FROM PersonList WHERE Name = ?",@"John”]; |