2012-09-25 82 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