2 mr me Mr_me 于 2012.09.25 13:53 提问

在SQLITE数据库中插入值

在SQLITE数据库中插入值,但是实现不了。代码中的数值都是varchar 类型。
代码如下:

sqlite3_stmt *statement;

NSString *docsDir;
NSArray *dirPaths;
int ID;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     
NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];

databasePath = [[NSString alloc] initWithString: [docsDir  
stringByAppendingPathComponent: @"weather.sqlite"]];


const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO satish VALUES    

('jodhpur','hazy1','68','7','700','30','28','10sept')"];

const char *insert_stmt = [insertSQL UTF8String];

sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
{
    NSLog(@"%@",statement);
    sqlite3_bind_text(statement, 1, insert_stmt, -1, SQLITE_TRANSIENT );

    if (sqlite3_step(statement) == SQLITE_ROW)
    {
        ID = sqlite3_last_insert_rowid(contactDB);

        NSLog(@"Data inserted successfully ");

    } 
    else{             
        NSLog(@"Failed to add contact");
    }
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}

1个回答

MrsSeven7
MrsSeven7   2012.09.25 15:44
已采纳
//试试下面的代码  
// 需要在数据库里插入列值

 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) {
        //*************** 在数据库中插入值******************************\\ 

        const char *sql = "insert into satish (firstname,lastname,email,company,phone) VALUES ('sdcbb','bbbb','bbbb','bbbb',1111122)";
        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);
    }
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!