problem in reading image from data base in iphone - iphone

hi i am able to store the image into database by using the following code.......
-(void)insertimages: (NSData *)image
{
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSUInteger len = [image length];
NSLog(#"data size is %d", len);
sqlStatement="insert into messages values(10,?)";
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
//sqlite3_bind_int(compiledStatement, 1, -1);
//sqlite3_bind_blob(updateStmt, 3, [imgData bytes], [imgData length], NULL);
sqlite3_bind_blob(compiledStatement, 1, [image bytes], [image length], SQLITE_TRANSIENT);
//sqlite3_bind_text(compiledStatement, 1, [SMSBody UTF8String],-1,SQLITE_STATIC);
if(sqlite3_step(compiledStatement) == SQLITE_DONE)
{
sqlite3_finalize(compiledStatement);
}
}
sqlite3_close(database);
}
}
but now my problem is i am not able to retrieve the image from the database and to display it in uiimageview...
con any one please help me how to do that.

Use following method to read the image data from database and stored the images in array or in dictionary
-(void) readImageDataFromDatabase {
// Setup the database object
sqlite3 *database;
// Init the img Array
imageArray = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from messages";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]];
];
NSData *imgData = [NSData dataWithContentsOfURL: url];
// Create a new image object with the data from the database
iconImage.image=[UIImage imageWithData:imgData];
// Add the img object to the img Array
[imageArray addObject:iconImage];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}

I was trying to do this a year ago, I wrote code to save the images into a sqlite3 db using osx sdk (of which i was able to write and read, i could even store the images in the db with ruby and read them on with macosx sdk). But when i moved this exact code over to an iOS app it would pull out bad data. If you do work this out i'd like to know the answer.

Related

Iinsert/Replace data in SQLite

Why can't I update data to SQLite eventhought it print "yes yes", please help, here my code, it called from viewdidload:
-(void)updateData{
CryptTestAppDelegate *delegate=(CryptTestAppDelegate *)[[UIApplication sharedApplication] delegate];
sqlite3_stmt *stmt=nil;
NSString *dd = #"testing";
const char *sql = "Update ProvPuzz set desc2=?";
sqlite3_prepare_v2(delegate.db, sql, 1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, [dd UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_step(stmt)){
NSLog(#"yes yes");
}else{
NSLog(#"no no");
}
sqlite3_finalize(stmt);
sqlite3_close(delegate.db);
}
It seems to pass every step, but my data not change at all. Any help please...
How should I call/code to be able to insert/replace these record in SQLite?
NSString *UpdateSql = [NSString stringWithFormat:#"Update ProvPuzz set desc2 = something"];
const char *sqlStatement = [UpdateSql UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(filesDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
if(sqlite3_step(compiledStatement) == SQLITE_DONE)
{
sqlite3_reset(compiledStatement);
}
}
// Release the compiled statement from memory
sqlite3_reset(compiledStatement);
sqlite3_finalize(compiledStatement);
sqlite3_close(filesDB);
and also check you db connection opened properly or not

Performance issue in iOS-5 for Sqlite

I am facing one problem while using sqlite in iOS 5. I am fetching records from two tables: one in Recipe & other in Ingredients from one Menu.db
From Recipe table I get all record and one recipeid on that basis I fetch records from ingredients table. It takes no time to fetch record when run on iOS 4.2 but when I run on iOS 5 it takes time to fetch the records. See the following code:
NSString *query = [NSString stringWithFormat:#"select id from Recipes"];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
rcp.recipeID = sqlite3_column_int(selectstmt, 0);
NSString *sql = [NSString stringWithFormat:#"select Name from Ingredients where recipeId = %d",rcp.recipeID];
sqlite3_stmt *stmt2;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt2, NULL) == SQLITE_OK) {
while(sqlite3_step(stmt2) == SQLITE_ROW) {}
}
}
}
Why is this issue coming in iOS 5.0, the same code runs fine on iOS 4.0, 4.2?
I know, code I have written is right,I want to know the exact reason behind this Performance issue in iOS 5.0 for Sqlite bcoz my app is totally build around database.
Try with using two different functions
After you finish with complete execution of your first query, start with second query.
For example :-
NSString *query = [NSString stringWithFormat:#"select id from Recipes"];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
rcp.recipeID = sqlite3_column_int(selectstmt, 0);
}
}
and then call
NSString *sql = [NSString stringWithFormat:#"select Name from Ingredients where recipeId = %d",rcp.recipeID];
sqlite3_stmt *stmt2;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt2, NULL) == SQLITE_OK) {
while(sqlite3_step(stmt2) == SQLITE_ROW) {}
Hope this helps to solve your issue.
I think you linked against libsqlite3.dylib. You should link the libsqlite3.0.dylib library instead.
If you want contever your .db to .sqlite
open your .db file select the table File-> Export--> Table from CSV (save your file with .csv format)
(like this way you select all table)
then open .sqlite file
File-> Import--> Table from CSV
after your .csv file choose a dialog box appear
in that Extract field names from first line must tick marked
now your sqlite file is ready.
put this file into your project
then set your .sqlite/.db file path
now set your select query as like this
#import <sqlite3.h>
-(void)SelectSqlData:(NSString *)SearchString
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"yourfileName.sqlite"];
sqlite3_stmt *compiledStatement;
sqlite3 *database;
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement;
sqlStatement = "select c.field1,c.field2,c.field3,c.field4 from YourTableName1 as c, YourTableName2 as b where b.Artist_Id = ?";
sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL);
//printf("\nError===%s",sqlite3_errmsg(database));
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement,1,[SearchString UTF8String] , -1,SQLITE_STATIC);
while(sqlite3_step(compiledStatement) == SQLITE_ROW )
{
NSString *str_field1=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *str_field2=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *str_field3=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *str_field4=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// add str_field into array
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
This probably isn't the answer you're looking for, but here's a small tip to improve performance.
NSString *query = [NSString stringWithFormat:#"select id from Recipes"];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
rcp.recipeID = sqlite3_column_int(selectstmt, 0);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//NSString *sql = [NSString stringWithFormat:#"select Name from Ingredients where recipeId = %d",rcp.recipeID];//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sqlite3_stmt *stmt2;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt2, NULL) == SQLITE_OK) {
while(sqlite3_step(stmt2) == SQLITE_ROW) {}
}
}
}
Every iteration of the while loop, you create a new NSString object (NSString *sql = ...), so maybe you should instead do this:
NSString *query = [NSString stringWithFormat:#"select id from Recipes"];
NSString *sql = [NSString stringWithFormat:#"select Name from Ingredients where recipeId = %d",rcp.recipeID];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
rcp.recipeID = sqlite3_column_int(selectstmt, 0);
sqlite3_stmt *stmt2;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt2, NULL) == SQLITE_OK) {
while(sqlite3_step(stmt2) == SQLITE_ROW) {}
}
}
}
Hope this helps a bit!
The function GetListBySQL is optimized and iOS versions independent. May it will help you out.
-(NSMutableArray*)GetListBySQL:(NSString*)SQL
{
NSMutableArray* Array;
Array=[[NSMutableArray alloc]init];
NSStringEncoding enc = [NSString defaultCStringEncoding];
sqlite3_stmt *select_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &select_statement, NULL) != SQLITE_OK) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
}
int columncount=sqlite3_column_count(select_statement);
NSMutableDictionary* dic;
while (sqlite3_step(select_statement) == SQLITE_ROW)
{
dic=[[NSMutableDictionary alloc]init];
for(int j=0;j<columncount;j++)
{
if(sqlite3_column_text(select_statement, j)!=nil)
[dic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(select_statement, j)] forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
else
[dic setObject:#"" forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
}
[Array addObject:dic];
[dic release];
}
sqlite3_finalize(select_statement);
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray: Array];
[Array release];
return arr;
}
Another alternative is to change SQLite to a Key/Value database like LevelDB (from google) or TokyoCabinet. I'm using LevelDB for two project right now and is working really good, and I used TokyoCabinet in the past also, the problem with TokyoCabinet is that is LGPL, so I'm not sure if is fully compatible with the iOS environment, but anyway I had several Apps in the appstore using Tokyo Cabinet (don't tell Apple).
For using both of them you will need a wrapper (Or maybe you can develop your own). This is a quick comparison and the available wrappers:
LevelDB: It seems to be one of the fastest out there (if not the fastest, take a look at their benchmarks). And as wrapper I'm currently using NULevelDB, if you have any problems adding it to your project let me know (I had some).
TokyoCabinet: It seems to be no so fast as LevelDB (I haven't run tests, I dropped it because of the license problems), but in the official page they recommend using their new library called KyotoCabinet that I haven't tested yet but is supposed to be faster. The wrapper I used was made by the amazing Aaron Hillegass, and it is called BNRPersistence.
As a recommendation, give a try to LevelDB, there is a bigger community behind, and the wrapper (NULevelDB) is simple and friendly.
Good luck!

To retrieve BLOB image from sqlite

The code for saving image:
NSData *imageData=UIImagePNGRepresentation(animalImage);
NSString *insertSQL=[NSString stringWithFormat:#"insert into AnimalsTable (name,propertyID,animalID,breed,mainBreed,dateofbirth,sex,notes,imageData) values(\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")",nameString,propertyString,animalidString,breedString,mainBreedString,dateString,sexString,notesString,imageData];
sqlite3_stmt *addStatement;
NSLog(#"%#",appDelegate.sqlFile);
const char *insert_stmt=[insertSQL UTF8String];
if (sqlite3_open([appDelegate.sqlFile UTF8String],&database)==SQLITE_OK) {
sqlite3_prepare_v2(database,insert_stmt,-1,&addStatement,NULL);
if (sqlite3_step(addStatement)==SQLITE_DONE) {
sqlite3_bind_blob(addStatement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
NSLog(#"Data saved");
}
else{
//NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
NSLog(#"Some Error occured");
}
sqlite3_close(database);
For retrieving image:
NSString *select_sql=[NSString stringWithFormat:#"select name,animalID,imageData from AnimalsTable where mainBreed='%#' AND breed='%#'",mainString,subString];
const char *sql = [select_sql UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *animalName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
NSString *animalid=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, 2) length: sqlite3_column_bytes(selectstmt, 2)];
[animalNamesArray addObject:animalName];
[animalIDArray addObject:animalid];
[imageDataArray addObject:dataForCachedImage];
}
}
}
else
sqlite3_close(database);
In UITableView CellForIndexPath:
NSData *dataForCachedImage=[imageDataArray objectAtIndex:indexPath.row];
UIImage *dataImage=[[UIImage alloc] init];
dataImage=[UIImage imageWithData:dataForCachedImage];
cell.imageView.image=dataImage;
When I debug the code:
I get bytes for NSData=226381 bytes And for dataImage 0x0.
Please help me.
You need to properly bind your values to the query for it to work. When you set the query on the first line, the description of the data would be inserted and not the correct data. If you were to log the query you would likely see something like <0FFAEC32 ... 23F0E8D1>.
You then attempted to bind the blob properly later but since your query was not written correctly it had no effect.
//Although you try to bind a blob here it does not get bound
//to anything since you do not include a parameter template.
sqlite3_bind_blob(addStatement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
To fix this here is a minimal example:
//query does not need to be an NSString* but just a const char *
//replace all %# with ?
const char *sql = "INSERT INTO AnimalsTable(name, ..., imageData) values(?, ..., ?)";
if (sqlite3_open([appDelegate.sqlFile UTF8String],&database)==SQLITE_OK) {
sqlite3_prepare_v2(database,insert_stmt,-1,&addStatement,NULL);
//Bind all of the values here before you execute the statement
sqlite3_bind_text(addStatement, 1, [nameString UTF8String], -1, NULL);
...
sqlite3_bind_blob(addStatement, 9, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
if (sqlite3_step(addStatement)==SQLITE_DONE) {
NSLog(#"Data saved");
}
...
//You must finalize your statement before closing the database
sqlite3_finalize(addStatement);
sqlite3_close(database);
Using binded values helps prevent inserting invalid data which could be a SQL injection attack and improves query performance for queries that are run often.
Note*: If you are going to be doing a lot of SQL consider using FMDB or even Core Data.

Memory optimization for sqlite requests - help needed

I'm using two methods to r/w sqlite table:
+ (NSString *) getWeatherData:(int)rowID:(int)columnID {
NSString *savedWeatherData = [[NSString alloc] init];
if (sqlite3_open([[DBController getDBPath] UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from TABLE where id=?";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
sqlite3_bind_int(selectstmt, 1, rowID);
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Weather *weatherObj = [[Weather alloc] initWithPrimaryKey:primaryKey];
weatherObj.weatherData = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, columnID)];
savedWeatherData = weatherObj.weatherData;
[weatherObj release];
}
}
}
return [savedWeatherData autorelease];
}
And to save some data:
+ (void) saveDataToDataBase:(NSString *)columnToUpdate:(int)rowID:(NSString *)value {
if (sqlite3_open([[DBController getDBPath] UTF8String], &database) == SQLITE_OK) {
updateStmt = nil;
NSString *sqlString = [[#"update TABLE set " stringByAppendingString:columnToUpdate] stringByAppendingString:#"=? where id=?"];
const char *sql = [sqlString UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK) {
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
} else { // select statement ok
sqlite3_bind_text(updateStmt, 1, [value UTF8String], -1, SQLITE_TRANSIENT); // replace first ? with value
sqlite3_bind_int(updateStmt, 2, rowID); // replace second ? with rowID
if(SQLITE_DONE != sqlite3_step(updateStmt)) {
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
} else {
// NSLog(#"Update completed !!!");
}
sqlite3_reset(updateStmt);
}
sqlite3_finalize(updateStmt);
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
With the Instruments, I see pretty big memory consumption for sqlite.
Info: during app startup, cca 100 different kind of data is stored in DB - for each data, this saveDataToDataBase method is called. (In case of no internet connection - getWeatherData would be used - and again cca 100 different kind of data would be read)
Please, can you instruct me - is it possible to optimize memory consumption.
Thanks a lot!
Kind regards!

sqlite3 insert and read BLOB data in database

I need to read and write BLOB data to a database. Here is my structure table
#define CREATE_TABLE_USERS_SQL "CREATE TABLE IF NOT EXISTS %# ( \
UserID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \
Name VARCHAR(50), \
Image BLOB);"
How can I insert it into database, and then retrieve from it?
Environment: iPhone SDK 4.1 SQLite3 database.
This code fails:
NSData * buf2 = [[NSData alloc] init];
sqlite3_column_blob(statement, 5);
buf2 = sqlite3_column_bytes(statement, 5);
user.image = [UIImage imageWithData: buf2];
Thanx all!! With yours help I'v solved problem and want to share results for future beginners like I am.)
-(void) addToDB
{
NSLog(#"\nCreating db");
NSString *str = #"CREATE TABLE IF NOT EXISTS Images (image1 BLOB);";
int res = SQLITE_ERROR;
res = sqlite3_open([#"aa.sql" UTF8String], &database);
res = sqlite3_exec(database, [str UTF8String], NULL, NULL, NULL);
sqlite3_stmt *updStmt =nil;
const char *sql = "INSERT INTO Images (image1) VALUES (?);";
res = sqlite3_prepare_v2(database, sql, -1, &updStmt, NULL);
if(res!= SQLITE_OK)
{
NSLog(#"Error while creating update statement:%s", sqlite3_errmsg(database));
}
UIImage *img = [UIImage imageNamed: #"flower.png"];
NSData *imageData = [NSData dataWithData: UIImagePNGRepresentation(img)];
res = sqlite3_bind_blob(updStmt, 1, [imageData bytes], [imageData length] , SQLITE_TRANSIENT);
if((res = sqlite3_step(updStmt)) != SQLITE_DONE)
{
NSLog(#"Error while updating: %#", sqlite3_errmsg(database));
sqlite3_reset(updStmt);
}
res = sqlite3_reset(updStmt);
res = sqlite3_close(database);
}
-(void) readFromDB
{
NSLog(#"\nReading from db");
NSString *query = #"SELECT image1 from Images";
int res = SQLITE_ERROR;
int len = 0;
res = sqlite3_open([#"aa.sql" UTF8String], &database);
sqlite3_stmt *statement;
res = sqlite3_prepare_v2 (database, [query UTF8String], -1, &statement, nil);
if (res == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
len = sqlite3_column_bytes(statement, 0);
NSData *imgData = [[NSData alloc] initWithBytes: sqlite3_column_blob(statement, 0) length: len];
UIImage *img = [[UIImage alloc] initWithData:imgData];
self.view1.image = img;
}
}
sqlite3_finalize(statement);
res = sqlite3_close(database);
}
Apart from choosing your client or programming interface, usage does not differ from any other string field.
[Update] I haven't had the luck to develop for the iPhone yet, but I believe it's the same as any other SELECT or INSERT query. Make sure to encode the BLOB and enclose it with single apostrophes (') like strings.
why not use fmdb by Gus Mueller et al, of Flying Meat? http://flyingmeat.com/
https://github.com/ccgus/fmdb
If you find fmdb useful, go and buy one of the excellents apps of Flying Meat. VoodooPad or Acron.
//-----insert IMAGE
- (void)setImage:(UIImage *)theImage
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *insertProgrammeSql = #"INSERT INTO imageTable (imageName) VALUES (?)";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(myDatabase, [insertProgrammeSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
NSData *imageData = UIImagePNGRepresentation(theImage);
sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
sqlite3_step(statement);
}
sqlite3_close(myDatabase);
// return YES;
}
}
//--------get image
-(UIImage *)getImage
{
UIImage *image = nil;
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *selectSql = #"SELECT image FROM imageTable";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(myDatabase, [selectSql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
int length = sqlite3_column_bytes(statement, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0 ) length:length];
image = [UIImage imageWithData:imageData];
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
return image;
}
This code fails:
NSData * buf2 = [[NSData alloc] init];
sqlite3_column_blob(statement, 5);
buf2 = sqlite3_column_bytes(statement, 5);
user.image = [UIImage imageWithData: buf2];
You are calling the SQLite functions in the correct order. According to the SQLite docs:
The safest and easiest to remember policy is to invoke these routines
in one of the following ways:
sqlite3_column_text() followed by sqlite3_column_bytes()
sqlite3_column_blob() followed by sqlite3_column_bytes()
sqlite3_column_text16() followed by sqlite3_column_bytes16()
In other words, you should call sqlite3_column_text(),
sqlite3_column_blob(), or sqlite3_column_text16() first to force the
result into the desired format, then invoke sqlite3_column_bytes() or
sqlite3_column_bytes16() to find the size of the result. Do not mix
calls to sqlite3_column_text() or sqlite3_column_blob() with calls to
sqlite3_column_bytes16(), and do not mix calls to
sqlite3_column_text16() with calls to sqlite3_column_bytes().
However, buff2 is an integer, not a data pointer. sqlite3_column_bytes tells you how many bytes are in the blob.