将数据添加到SQLite数据库

时间:2012-04-02 12:13:59

标签: iphone ios

以下代码是将数据添加到SQLite数据库;

        NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO FruitsTable name,qty,amt,date VALUES \"%@\",\"%@\",\"%d\",\"%@\"",fruits.fruitName,fruits.qty,fruits.amount,fruits.date];
        NSLog(@"query %@",insertSQL);
        const char *insert_stmt = [insertSQL UTF8String];

        sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog(@"Row added");
        } 

        else {
            NSLog(@"Failed to add row");
        }
        sqlite3_finalize(statement);
        sqlite3_close(database);

无法添加行..因为在Statement中获取空值。

1 个答案:

答案 0 :(得分:0)

查看我将数据插入sql的工作示例

    NSDate* date = [NSDate date];
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* str = [formatter stringFromDate:date];
    sqlite3 *database;
    ///////
    sqlite3_stmt *compiledStmt;
    if(sqlite3_open([dbPath UTF8String], &database) ==SQLITE_OK) {

        sqlite3_prepare_v2(database, "BEGIN TRANSACTION", -1, &compiledStmt, NULL);
        sqlite3_step(compiledStmt);
        sqlite3_finalize(compiledStmt);

        const char *sqlInsertQry="insert into bookmarks(book_id,description,entry_date,page_no) values(?,?,?,?)";
        if(sqlite3_prepare_v2(database, sqlInsertQry, -1, &compiledStmt, NULL) == SQLITE_OK ){
            sqlite3_bind_int(compiledStmt,1,[[bookdetail valueForKey:@"bookid"] intValue]); 
            sqlite3_bind_text(compiledStmt,2,[[bookdetail valueForKey:@"text"] UTF8String],-1,SQLITE_TRANSIENT);
            sqlite3_bind_text(compiledStmt,3,[str UTF8String],-1,SQLITE_TRANSIENT);
            sqlite3_bind_int(compiledStmt,4,[[bookdetail valueForKey:@"page"] intValue]); 

                NSUInteger err = sqlite3_step(compiledStmt);
                if (err != SQLITE_DONE){
                    NSLog(@"error while binding %d %s",err, sqlite3_errmsg(database));
                }
                sqlite3_reset(compiledStmt);
            sqlite3_finalize(compiledStmt);     
        } else {
            NSLog(@"Invalid Query");
        }

        sqlite3_prepare_v2(database, "END TRANSACTION", -1, &compiledStmt, NULL);
        sqlite3_step(compiledStmt);
        sqlite3_finalize(compiledStmt); 
        sqlite3_close(database);
        return YES;
    } else {
        NSLog(@"error while opening database.");
        return NO;
    }