标签:
转自:http://www.cnblogs.com/wuhenke/archive/2012/02/07/2341656.html
使用资料库的第一件事,就是建立一个资料库。要注意的是,在iOS环境下,只有document directory 是可以进行读写的。在写程式时用的那个Resource资料夹底下的东西都是read-only。因此,建立的资料库要放在document 资料夹下。方法如下:
1 |
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); |
2 |
NSString *documentDirectory = [paths objectAtIndex:0]; |
3 |
NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@ "MyDatabase.db" ]; |
4 |
FMDatabase *db = [FMDatabase databaseWithPath:dbPath] ; |
5 |
if (![db open]) { |
6 |
NSLog(@“Could not open db.”); |
7 |
return ; |
8 |
} |
建立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]; |
1 |
//找地址 |
2 |
3 |
NSString *address = [db stringForQuery:@ "SELECT Address FROM PersonList WHERE Name = ?" ,@"John”]; |
4 |
5 |
//找年齡 |
6 |
7 |
int age = [db intForQuery:@ "SELECT Age FROM PersonList WHERE Name = ?" ,@"John”]; |
标签:
原文地址:http://www.cnblogs.com/wangpei/p/4331904.html