iphone - 将值插入sqlite数据库

时间:2012-08-06 12:18:23

标签: iphone objective-c ios xcode sqlite

我正在尝试在iphone应用程序中将值插入我的sqlite数据库,但没有成功:

insertSQL = [NSString stringWithFormat: @"INSERT INTO eventslist (date, title, description) VALUES ('%@', '%@', '%@')", dateString, title, descr];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(eventsDB, insert_stmt, -1, &statement, NULL);

我的descr变量包含一些带有特殊字符,新行字符等的文本。我认为这是一个原因。我该如何解决?

3 个答案:

答案 0 :(得分:4)

+(void)CheckConnection
{
    NSArray *docpath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docdir = [docpath objectAtIndex:0];
    dbpath=[docdir stringByAppendingPathComponent:databasename];
    BOOL success;
    NSFileManager *fm = [NSFileManager defaultManager];
    success=[fm fileExistsAtPath:dbpath];
    if(success)
    {
        return;
    }
    NSString *dbPathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:databasename];
    [fm copyItemAtPath:dbPathFromApp toPath:dbpath error:nil];
}

+(BOOL)Savedata:(NSDictionary*)dicval
{
    [self CheckConnection];
    BOOL sucsess;
    sqlite3 *database;

    if (sqlite3_open([dbpath UTF8String], &database)==SQLITE_OK) {
        NSString *query=[NSString stringWithFormat:@"insert into emp_info values(NULL,'%@','%@','%@','%@')",[dicval valueForKey:@"name"],[dicval valueForKey:@"surname"],[dicval valueForKey:@"mobile_no"],[dicval valueForKey:@"city"]];
        const char *sqlStmt=[query UTF8String];
        sqlite3_stmt *cmpSqlStmt;
        int rv=sqlite3_prepare_v2(database, sqlStmt, -1, &cmpSqlStmt, NULL);

        sucsess=((rv ==SQLITE_OK)? YES : NO);
        sqlite3_step(cmpSqlStmt);
        sqlite3_finalize(cmpSqlStmt);
    }
    sqlite3_close(database);
    return sucsess;

}

答案 1 :(得分:1)

此链接包含从数据库创建,插入和检索数据,这可能会有所帮助。

Creating an SQLite3 database file through Objective-C

首先创建数据库并打开它。然后只尝试将数据插入数据库。

答案 2 :(得分:0)

if(sqlite3_open([databasePath UTF8String],&db) == SQLITE_OK)
{
    insertSQL = [NSString stringWithFormat: @"INSERT INTO eventslist (date, title, description) VALUES ('%@', '%@', '%@')", dateString, title, descr];

    char *errmsg=nil;

    if(sqlite3_exec(db, [insertSQL UTF8String], NULL, NULL, &errmsg)==SQLITE_OK)
    {
       NSLog(@"Row Inserted");
    }
}
sqlite3_close(db);