- FMDatabase 提供方法來透過SQL與DB溝通
- FMResultSet 與Java的Cursor物件類似
產生DB
// 設定Label元件在文字內容超過框架時的樣式 content.lineBreakMode = UILineBreakModeWordWrap; // 設定Label元件最多顯示的行數,0為不限 content.numberOfLines = 0; // 透過NSFileManager取得Document的路徑 NSURL* url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; // 在Document下新增DB檔案 NSString* dbPath = [[url path] stringByAppendingPathComponent:@"myDB.db"]; // 透過FMDatabase物件與DB溝通 db = [FMDatabase databaseWithPath:dbPath]; if(![db open]) { NSLog(@"Could not open database."); } if(![db executeUpdate:@"CREATE TABLE IF NOT EXISTS info (id INTEGER PRIMARY KEY, name TEXT, tel TEXT)"]) { NSLog(@"Could not creat table (%@)", [db lastErrorCode]); } |
插入資料
// VALUES後的格式需使用範例這樣的方法,否則會出錯 if(![db executeUpdate:@"INSERT INTO info (name, tel) VALUES (?, ?)",@"Vince",@"9988765"]) { NSLog(@"Could not insert"); } |
取得資料
FMResultSet* rs = [db executeQuery:@"SELECT * FROM info"]; // 印出所有Query到的資料 while([rs next]) { int _id = [rs intForColumn:@"id"]; NSString* name = [rs stringForColumn:@"name"]; NSString* tel = [rs stringForColumn:@"tel"]; NSMutableString* strTemp = [NSMutableString stringWithString:content.text]; if([strTemp compare:@"Label"]) { [strTemp appendFormat:@"%d-%@-%@\n", _id, name, tel]; content.text = strTemp; }else { content.text = [NSString stringWithFormat:@"%d-%@-%@\n", _id, name, tel]; } } |
沒有留言:
張貼留言