如何将数据保存到sqlite数据库的不同表中

时间:2012-08-22 04:55:45

标签: iphone ios sqlite

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

2 个答案:

答案 0 :(得分: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: 上述方法是必要的,因为如果任何用户使用单个cote输入数据,那么它将导致您的应用程序崩溃。(如果您不从用户那里获取输入,则可以删除它)

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

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

答案 1 :(得分:0)

如果您正在使用SQLite,请转到FMDB,因为它会让您的生活更轻松。上面的所有代码都可以缩小为类似线程安全的调用(在我的头顶,所以可能没有编译就绪)。

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

        DLog(@"insert error: %@", [db lastErrorMessage]);
    }];