2012-09-25 48 views
-1

有插入图像与其他领域的代码:无法将图像添加到sqlite数据库?

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]; 

认为

+0

我什么都没有丢失,因为它的工作原理没有像我只是放一些代码来解释,这不是整个代码 – user1426954

回答

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); 
+0

+1,但有时只存储图像的位置可能会更好。 (这样,图像不必发送尽可能多) – Aleph

+0

它的工作完全抱歉我已经改变了BD的名称,它的工作原理:) – user1426954