开发者

How to insert into table (sqlite db) in iphone sdk

How can I 开发者_如何学Pythoninsert data into an sqlite DB in iphone sdk (xcode)? thank you!


First you need to initialise the db with these 2 methods

-(id) initDatabase{
    databaseName = @"db.sqlite";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    [databasePath retain];

    return self;
}

-(void) checkAndCreateDatabase{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    success = [fileManager fileExistsAtPath:databasePath];
    if(success) return;
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    [fileManager release];
}

Then you can interact with it :

if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    static sqlite3_stmt *compiledStatement;
    sqlite3_exec(database, [[NSString stringWithFormat:@"insert into myTable (var1, var2) values ('%@', '%@')", myVar1, myVar2] UTF8String], NULL, NULL, NULL);
    sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);


it easy to store data in DB

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath =[documentsDir stringByAppendingPathComponent:@"register.sqlite"];
    BOOL success = [fileManager fileExistsAtPath:dbPath]; 
    sqlite3_stmt *selectstmt;
    if(!success)
    {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"register.sqlite"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success) 
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
        //*************** insert value in database******************************\\ 

        const char *sql = "insert into reg_FORM (firstname,lastname,email,company,phone) VALUES ('nannav','cs','nannav@gmail.com','ibm',123456789)";
        sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL); 
        if(sqlite3_step(selectstmt)==SQLITE_DONE)
        {
            NSLog(@"insert successfully");
        }
        else
        {
            NSLog(@"insert not successfully");

        }
    sqlite3_finalize(selectstmt);
        sqlite3_close(database);
    }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜