0

我是 ios 中 sqlite 的新手。因此,为了将数据保存到数据库的不同表中,我必须首先和下一步做什么?

4

2 回答 2

0

我在我的各种应用程序中使用了 Sqlite 数据库,它对我来说很好用。您必须按照以下步骤将数据插入 Sqlite 数据库的表中...

1.首先你需要创建你的数据库......我希望你已经创建并插入到你的项目中,并添加了链接框架 libsqlite3.0.dylib 并在你的类中导入这些。2.替换你的插入方法写这段代码...

+(void)insertRecord:(NSString *)dbPath record:(NSMutableArray*)dataArray{
    @try{
        sqlite3_stmt *insertStmnt;
        if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){

            for(int i=0; i<[dataArray count]; i++){
                id record=[dataArray objectAtIndex:i];
                NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO Table_Name (\"Column1\",\"Column2\",\"Column3\",\"Column4\",) VALUES('%@','%@','%@','%@')",[[record objectForKey:@"col1"]  stringByReplacingOccurrencesOfString:@"'" withString:@"''"],[[record objectForKey:@"col2"] stringByReplacingOccurrencesOfString:@"'" withString:@"''"],[[record objectForKey:@"col3"]  stringByReplacingOccurrencesOfString:@"'" withString:@"''"],[[record objectForKey:@"col4"]  stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];

                const char *sql = [insertQuery cStringUsingEncoding:NSUTF8StringEncoding];

                if(sqlite3_prepare_v2(database, sql, -1, &insertStmnt, NULL) == SQLITE_OK){

                }else{

                }
                if(SQLITE_DONE != sqlite3_step(insertStmnt)){

                }


            }
        }
    }@catch (NSException *r) {
        NSLog(@"UU %@",r);
    } 
}

其中 record 是字典数组,其中包含您要在表中插入的值或从用户那里获取的值。stringByReplacingOccurrencesOfString:上述方法是必要的,因为如果任何用户输入单个数据,则会导致您的应用程序崩溃。(如果您不接受用户输入,您可以将其删除)

是的,您也可以按照这些链接更好地理解.. 1.http://www.techotopia.com/index.php/IOS_4_iPhone_Database_Implementation_using_SQLite 2.SQLite 教程

希望它对你有用,如果你有任何疑问,可以回复..

于 2012-08-22T05:51:35.023 回答
0

如果你使用 SQLite,那么就去获取FMDB,因为它会让你的生活更轻松。上面的所有代码都可以缩减为线程安全调用,例如(在我的脑海中,所以可能没有准备好编译)。

[queue inDatabase:^(FMDatabase *db) {
        [db executeUpdateWithFormat:@"INSERT OR REPLACE INTO table (f1,f2) VALUES (%@, %@);", field1, field2];

        DLog(@"insert error: %@", [db lastErrorMessage]);
    }];
于 2012-08-22T07:58:08.220 回答