日期:2014-05-16 浏览次数:20485 次
$ sqlite3 sample.db sqlite> CREATE TABLE TEST( ...> id INTEGER PRIMARY KEY, ...> name VARCHAR(255) ...> );
svn co http://flycode.googlecode.com/svn/trunk/fmdb fmdb
BOOL success; NSError *error; NSFileManager *fm = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"]; success = [fm fileExistsAtPath:writableDBPath]; if(!success){ NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"]; success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; if(!success){ NSLog([error localizedDescription]); } } // 连接DB FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath]; if ([db open]) { [db setShouldCacheStatements:YES]; // INSERT [db beginTransaction]; int i = 0; while (i++ < 20) { [db executeUpdate:@"INSERT INTO TEST (name) values (?)" , [NSString stringWithFormat:@"number %d", i]]; if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); } } [db commit]; // SELECT FMResultSet *rs = [db executeQuery:@"SELECT * FROM TEST"]; while ([rs next]) { NSLog(@"%d %@", [rs intForColumn:@"id"], [rs stringForColumn:@"name"]); } [rs close]; [db close]; }else{ NSLog(@"Could not open db."); }
$ sqlite3 sample.db sqlite> CREATE TABLE TbNote( ...> id INTEGER PRIMARY KEY, ...> title VARCHAR(255), ...> body VARCHAR(255) ...> );
//TbNote.h #import <Foundation/Foundation.h> @interface TbNote : NSObject { int index; NSString *title; NSString *body; } @property (nonatomic, retain) NSString *title; @property (nonatomic, retain) NSString *body; - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody; - (int)getIndex; @end //TbNote.m #import "TbNote.h" @implementation TbNote @synthesize title, body; - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{ if(self = [super init]){ index = newIndex; self.title = newTitle;