无法将图像添加到sqlite数据库?

时间:2012-09-25 14:00:08

标签: xcode image sqlite add

有将代码插入其他字段的代码:

UIImage *image1 = [UIImage imageNamed:@"recette.jpg"];
            NSData *image2 = UIImagePNGRepresentation(image1);

    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CONTACTS (name, address, phone,image) VALUES (\"%@\", \"%@\", \"%@\", \"%@\" )", name.text, address.text, phone.text,image2];

认为

1 个答案:

答案 0 :(得分:2)

图像需要添加为blob对象

UIImage *image1 = [UIImage imageNamed:@"recette.jpg"];
NSData *imgData = UIImagePNGRepresentation(image1);
sqlite3_stmt *stmt;

char *update = "INSERT INTO CONTACTS (name, address, phone,image) VALUES (?, ?, ?, ?);";

if (sqlite3_prepare_v2(dbpath, update, -1, &stmt, nil) == SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, name.text, -1, NULL);
        sqlite3_bind_text(stmt, 2, address.text, -1, NULL);
        sqlite3_bind_text(stmt, 3, phone.text, -1, NULL);
        if(imgData != nil)
            sqlite3_bind_blob(stmt, 4, [imgData bytes], [imgData length], NULL);
        else
            sqlite3_bind_blob(stmt, 4, nil, -1, NULL);

 }
 else if (sqlite3_step(stmt) != SQLITE_DONE){
     char *errorMsg;
     NSAssert1(0, @"Error updating table: %s", errorMsg);
}

    sqlite3_finalize(stmt);