原文地址: https://github.com/ccgus/fmdb
更多的使用,大家可以看看source中的README.markdown
使用资料库的第一件事,就是建立一个资料库。要注意的是,在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 (?,?,?,?,?,?)" , |
2 |
3 | @ "Jone" , [NSNumber numberWithInt:20], [NSNumber numberWithInt:0], @“091234567”, @“Taiwan, R.O.C”, [NSData dataWithContentsOfFile: filepath]]; |
1 | [db executeUpdate:@ "UPDATE PersonList SET Age = ? WHERE Name = ?" ,[NSNumber numberWithInt:30],@“John”]; |
01 | FMResultSet *rs = [db executeQuery:@ "SELECT Name, Age, FROM PersonList" ]; |
02 |
03 | while ([rs next]) { |
04 |
05 | NSString *name = [rs stringForColumn:@ "Name" ]; |
06 |
07 | int age = [rs intForColumn:@ "Age" ]; |
08 |
09 | } |
10 |
11 | [rs close]; |
NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name = ?",@"John”];
int age = [db intForQuery:@"SELECT Age FROM PersonList WHERE Name = ?",@"John”];