Image not store in sqlite - ios

I made one demo which stores an Image to the database. Currently I am not getting any error but my image is not store in sqlite database.
Please see the below code and tell me where is my mistake.
DBManager class
sqlite3 *sqlite3DatabaseObject;
sqlite3_stmt* sqlite3Statement;
-(void)database
{
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:databasePath] == NO) {
const char *dbPath = [databasePath UTF8String];
if (sqlite3_open(dbPath, &sqlite3DatabaseObject)== SQLITE_OK) {
char * errorMessage;
const char *sqlite3Query = "CREATE TABLE IF NOT EXISTS PICTURES (PHOTO BLOB)";
if (sqlite3_exec(sqlite3DatabaseObject, sqlite3Query, NULL, NULL, &errorMessage)!= SQLITE_OK) {
NSLog(#"failed = %#",sqlite3DatabaseObject);
}
sqlite3_close(sqlite3DatabaseObject);
}else{
NSLog(#"failed to create database");
}
}
}
- (void) SaveImagesToSql: (NSData*) imgData {
NSString *databasePath = [[NSBundle mainBundle] pathForResource:#"informationdb" ofType:#"sql"];
const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)";
int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
if (openDatabaseResult == SQLITE_OK) {
int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
if( sqlite3Prepare == SQLITE_OK ) {
sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
sqlite3_step(sqlite3Statement);
}
else
{
NSLog(#"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject));
}
sqlite3_finalize(sqlite3Statement);
}
else NSLog( #"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject) );
sqlite3_close(sqlite3DatabaseObject);
}
ViewController class
- (void)viewDidLoad {
[super viewDidLoad];
DBManager * dbmClass = [[DBManager alloc]init];
[dbmClass database];
imgView.userInteractionEnabled = YES;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(uploadOrCapture)];
[singleTap setNumberOfTapsRequired:1];
[imgView addGestureRecognizer:singleTap];
}
- (IBAction)btnSave:(id)sender {
DBManager*dbmClass = [[DBManager alloc]init];
NSData *imageInData = UIImagePNGRepresentation(imgView.image);
[dbmClass SaveImagesToSql:imageInData];
[self dismissViewControllerAnimated:YES completion:nil];
}
I am not able to find out the issue. It successfully executes all the code but when I download the database from device and checked, there is no image data stored.
Thanks in advance.
Mihir.

just replace this function to my code because you got wrong database path
- (void) SaveImagesToSql: (NSData*) imgData {
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)";
int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
if (openDatabaseResult == SQLITE_OK) {
int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
if( sqlite3Prepare == SQLITE_OK ) {
sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
sqlite3_step(sqlite3Statement);
}
else
{
NSLog(#"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject));
}
sqlite3_finalize(sqlite3Statement);
}
else NSLog( #"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject) );
sqlite3_close(sqlite3DatabaseObject);
}
here this is database screenshot
Don't drag to database in your project.if any problem than tell me

Here How I do modify as per your use.
NSData *imageData = UIImagePNGRepresentation(imgView.image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];
dateFormatter.dateFormat = #"ddMMyyyyhhmmss_SSS_a";
NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
NSString *imageName=[NSString stringWithFormat:#"Image_%#",currentTime];
NSString *saveFilePath =[NSString stringWithFormat:#"%#.%#",imageName,#"png"]; //Store saveFilePath string to your database
NSString *localFilePath1 = [documentsDirectory stringByAppendingPathComponent:saveFilePath];
[imageData writeToFile:localFilePath1 atomically:YES];
Hope it helps you.

Related

Image not retrieving from sql database in objective c

Hello I have been trying to retrieve image from sql database named informationdb.sql but I am not able to,could anyone help with that.Here is my code
- (NSData*) LoadImagesFromSql
{
NSData* data = nil;
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
if (openDatabaseResult == SQLITE_OK) {
const char* sqlite3Query = "SELECT PHOTO FROM PICTURES";
int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
if( sqlite3Prepare == SQLITE_OK )
{
const char *myData = sqlite3_column_blob(sqlite3Statement, 1);
int myDataSize = sqlite3_column_bytes(sqlite3Statement, 1);
data = [NSData dataWithBytes:myData length:myDataSize];
sqlite3_step(sqlite3Statement);
}
sqlite3_finalize(sqlite3Statement);
}
sqlite3_close(sqlite3DatabaseObject);
return data;
}
Thank you.
first delete database in document directory than change all three method to my code
-(void)database
{
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
NSLog(#"database path=%#",databasePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:databasePath] == NO) {
const char *dbPath = [databasePath UTF8String];
if (sqlite3_open(dbPath, &sqlite3DatabaseObject)== SQLITE_OK) {
char * errorMessage;
const char *sqlite3Query = "CREATE TABLE IF NOT EXISTS PICTURES (PHOTO BLOB,Id integer PRIMARY KEY)";
if (sqlite3_exec(sqlite3DatabaseObject, sqlite3Query, NULL, NULL, &errorMessage)!= SQLITE_OK) {
NSLog(#"failed = %#",sqlite3DatabaseObject);
}
sqlite3_close(sqlite3DatabaseObject);
}else{
NSLog(#"failed to create database");
}
}
}
- (void) SaveImagesToSql: (NSData*) imgData {
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
NSLog(#"database path=%#",databasePath);
const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)";
int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
if (openDatabaseResult == SQLITE_OK) {
int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
if( sqlite3Prepare == SQLITE_OK ) {
sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
sqlite3_step(sqlite3Statement);
}
else
{
NSLog(#"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject));
}
sqlite3_finalize(sqlite3Statement);
}
else NSLog( #"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject) );
sqlite3_close(sqlite3DatabaseObject);
}
- (NSData*)LoadImagesFromSql
{
NSData* data = nil;
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
sqlite3_stmt *compiledStmt;
sqlite3 *db;
int i = 1;
if(sqlite3_open([databasePath UTF8String], &db)==SQLITE_OK){
NSString *insertSQL = [NSString stringWithFormat:#"SELECT PHOTO FROM PICTURES WHERE Id = %d",i];
if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStmt) == SQLITE_ROW) {
int length = sqlite3_column_bytes(compiledStmt, 0);
data = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length];
NSLog(#"Length : %lu", (unsigned long)[data length]);
// if(imageData == nil)
// NSLog(#"No image found.");
// else
// imgView.image = [UIImage imageWithData:imageData];
}
}
sqlite3_finalize(compiledStmt);
}
sqlite3_close(db);
return data;
}
solved it by this:
- (NSData*) LoadImagesFromSql
{
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [directoryPaths objectAtIndex:0];
NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:#"informationdb.sql"]];
NSData* data = nil;
// int i=0;
NSString* sqlite3Query = [NSString stringWithFormat:#"SELECT PHOTO FROM PICTURES "];
int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
if (openDatabaseResult == SQLITE_OK)
{
int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, [sqlite3Query UTF8String], -1, &sqlite3Statement, NULL);
if( sqlite3Prepare == SQLITE_OK )
{
while (sqlite3_step(sqlite3Statement) == SQLITE_ROW) {
const char *myData = sqlite3_column_blob(sqlite3Statement, 0);
int myDataSize = sqlite3_column_bytes(sqlite3Statement, 0);
data = [NSData dataWithBytes:myData length:myDataSize];
}
sqlite3_finalize(sqlite3Statement);
}
}
sqlite3_close(sqlite3DatabaseObject);
return data;
}
and updated viewWillAppear as :
-(void)viewWillAppear:(BOOL)animated{
dbmClass = [[DBManager alloc]init];
if (imgPic.image != nil) {
imgPic.image = nil;
}
imgPic.image = [UIImage imageWithData:[dbmClass LoadImagesFromSql]];
NSLog(#"%#",[dbmClass LoadImagesFromSql]);
}

Adding record to table in SQLIte file won't work

I'm trying to add record to SQLite file but nothing happens. I get no error and in console I get that record is inserted in table #"----> RECORD INSERTED". Below you can see the code that I'm using. Please, can someone tell me how to fix this. Thanks for your time and help.
- (void)addRecordToSQLiteDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:#"ProductiivData.sqlite"];
success = [fileManager fileExistsAtPath:appDBPath];
if (success)
{
const char *databaseCharPath = [appDBPath UTF8String];
if (sqlite3_open(databaseCharPath, &(database)) == SQLITE_OK)
{
char *errorInsert;
const char *insertRecordInPROJECT = "insert into PROJECT values (139, 'TEST1888799')";
if (sqlite3_exec(database, insertRecordInPROJECT, NULL, NULL, &errorInsert))
{
NSLog(#"----> RECORD INSERTED");
}
else
{
NSLog(#"----> RECORD NOT INSERTED -- Error: %s", errorInsert);
}
char *errorSelectAll;
sqlite3_stmt *statement = NULL;
const char *allRecordsFromPROJECT = "select * from PROJECT";
if (sqlite3_prepare_v2(database, allRecordsFromPROJECT, 1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *projectName = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
}
}
else
{
NSLog(#"----> RECORDS NOT SELECTED -- Error: %s", errorSelectAll);
}
}
}
}
Separate insert and select logic, Try following code
Get Database path
+ (NSString *)getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"dbName.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"dbName.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
return dbPath;
}
Insert Data
+ (void)insertData
{
const char *dbpath = [[self getDBPath] UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *strSQL = [NSString stringWithFormat:#"INSERT INTO tableName………………."];
const char *insertQuery = [strSQL UTF8String];
sqlite3_stmt *insert_stmt;
if (sqlite3_prepare_v2(database, insertQuery, -1, &insert_stmt, NULL) == SQLITE_OK)
{
if (sqlite3_step(insert_stmt) == SQLITE_DONE)
{
// Code
}
else
{
NSLog(#"error");
}
}
sqlite3_finalize(insert_stmt);
sqlite3_close(database);
}
else
{
NSLog(#"Error in opening database.");
}
}
Get data from table
+ (NSArray *)getDataList
{
NSMutableArray *arrProducts = [[NSMutableArray alloc] init];
const char *dbpath = [[self getDBPath] UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *strSQL = [NSString stringWithFormat:#"SELECT * FROM tableName"];
const char *selectQuery = [strSQL UTF8String];
sqlite3_stmt *select_stmt;
if(sqlite3_prepare_v2(database, selectQuery, -1, &select_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(select_stmt) == SQLITE_ROW)
{
NSInteger productID = sqlite3_column_int(select_stmt, 0);
NSString productNo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(select_stmt, 1)];
// Store above data into dictionary or object and then add this to array
[arrProducts addObject:dict];
}
}
}
else
{
NSLog(#"Error in opening database.");
}
return arrProducts;
}

Error while creating update statement. 'no such table: ***'

I have a sqlite db , with a "conjugare" table , but i'm getting this:
Error while creating update statement. 'no such table: conjugare'
I was trying to create a copy of databse . The database it could be open. I think that there is a problem with my file because it's possible to be read it like a txt file and not a sqlite ? I read about this in other question from stackoverflow and i was trying to implemnet it but no results.Any help for solve this , please?
+ (FailedBankDatabase*)database {
if (_database == nil) {
_database = [[FailedBankDatabase alloc] init];
}
return _database;
}
- (id)init {
if ((self = [super init])) {
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:#"conjugareDB" ofType:#"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(#"Failed to open database!");
}
else
[self createEditableCopyOfDatabaseIfNeeded];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the patht to the database file
NSString * databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent: #"conjugareDB.sqlite"]];
if (sqlite3_open([databasePath UTF8String], &_database) != SQLITE_OK) {
NSLog(#"Failed to open database!");
}
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] == NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &_database) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT";
if (sqlite3_exec(_database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"Failed to create table");
}
sqlite3_close(_database);
} else {
NSLog( #"Failed to open or create database");
}
}
}
return self;
}
- (void) createEditableCopyOfDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"conjugareDB.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"conjugareDB.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (void)dealloc {
sqlite3_close(_database);
[super dealloc];
}
- (NSArray *)failedBankInfos {
NSMutableArray *retval = [[[NSMutableArray alloc] init] autorelease];
NSString *query = #"select id from conjugare";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
int uniqueId = sqlite3_column_int(statement, 0);
char *nameChars = (char *) sqlite3_column_text(statement, 1);
char *cityChars = (char *) sqlite3_column_text(statement, 2);
char *stateChars = (char *) sqlite3_column_text(statement, 3);
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
NSString *city = [[NSString alloc] initWithUTF8String:cityChars];
NSString *state = [[NSString alloc] initWithUTF8String:stateChars];
FailedBankInfo *info = [[FailedBankInfo alloc] initWithUniqueId:uniqueId name:name city:city state:state];
[retval addObject:info];
[name release];
[city release];
[state release];
[info release];
}
sqlite3_finalize(statement);
}
else
{
NSLog(#"Error while creating update statement. '%s'", sqlite3_errmsg(_database));
}
return retval;
}
Go to Targets -> Build Phases -> Copy Bundle Resources click + on it & select Sqlite Database rdb file from resources.

select data record in table sqlite ios return with only one object

i have an problem when i select usernames the return is only one object and the table contain all of usernames how to solve this i try to select by database manager and i find that query sql statment is right
- (NSMutableArray*) FindAccounts
{
///database
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"TRIAL.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT USERNAME,TYPE FROM CONTNEW"];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(contactDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *USERS = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[resultArray addObject:USERS];
return resultArray;
}
else{
NSLog(#"Not found");
return nil;
}
sqlite3_reset(statement);
}
}
return nil;
}
OK, try this (note that there is not much error reporting):
- (NSMutableArray*) FindAccounts
{
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *databasePath = [docsDir stringByAppendingPathComponent:#"TRIAL.sqlite"];
sqlite3_stmt *statement;
// I assume contactDB is an instance variable?
if (!contactDB &&
sqlite3_open([databasePath UTF8String], &contactDB) != SQLITE_OK) {
NSLog(#"Failed to open database");
return nil;
}
NSString *querySQL = #"SELECT USERNAME,TYPE FROM CONTNEW ORDER BY USERNAME";
NSMutableArray *resultArray = [NSMutableArray new];
if (sqlite3_prepare_v2(contactDB, [querySQL UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *username = #(sqlite3_column_text(statement, 0));
[resultArray addObject:username];
}
sqlite3_reset(statement);
}
return resultArray;
}

SQLITE_MISUSE when trying to execute select query in iOS xcode

I have a class to access to my database and when I want an instance, I call this function
+(DatabaseHelper*) getInstanse
{
if (!instance) {
instance = [[super allocWithZone:NULL] init];
[instance createDatabase];
}
return instance;
}
and here is createDatabase function
-(void) createDatabase
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: databaseName]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
[self createTableProduct];
[self createTableCategory];
[self createTableState];
[self createTableAgency];
[self createTableNews];
[self createTableKnowledge];
[self createTableVideos];
[self createTableProductComment];
sqlite3_close(database);
}
else {
NSLog(#"Failed to open/create database");
}
}
}
I don't have problem with create database and insert into it but when I want execute select query it says sqlite_misuse
Here is my select query
-(NSMutableArray*) getAllAgencies
{
[self createEditableDatabase];
NSMutableArray *agencies = [[NSMutableArray alloc] init];
NSString *query = [[NSString alloc] initWithFormat:#"SELECT * FROM %#_%#", agencyTable, [Shares getLanguage]];
sqlite3_stmt *statement;
int sqlResult = sqlite3_prepare_v2(database, [query cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL);
if (sqlResult == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
int Id = sqlite3_column_int(statement, 0);
char *nameChars = (char *) sqlite3_column_text(statement, 1);
char *phoneChars = (char *) sqlite3_column_text(statement, 2);
char *addressChars = (char *) sqlite3_column_text(statement, 3);
char *faxChars = (char *) sqlite3_column_text(statement, 4);
char *emailChars = (char *) sqlite3_column_text(statement, 5);
char *detailsChars = (char *) sqlite3_column_text(statement, 6);
int stateID = sqlite3_column_int(statement, 7);
float latitude = (float) sqlite3_column_double(statement, 8);
float longtitude = (float) sqlite3_column_double(statement, 9);
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
NSString *phone = [[NSString alloc] initWithUTF8String:phoneChars];
NSString *address = [[NSString alloc] initWithUTF8String:addressChars];
NSString *fax = [[NSString alloc] initWithUTF8String:faxChars];
NSString *email = [[NSString alloc] initWithUTF8String:emailChars];
NSString *details = [[NSString alloc] initWithUTF8String:detailsChars];
AgencyData *data = [[AgencyData alloc] init];
[data setId:Id];
[data setName:name];
[data setPhone:phone];
[data setAddress:address];
[data setFax:fax];
[data setEmail:email];
[data setDetails:details];
[data setStateId:stateID];
[data setLatitude:latitude];
[data setLongtitude:longtitude];
[agencies addObject:data];
}
}
sqlite3_finalize(statement);
return agencies;
}
and here is createEditableDatabase function
- (void) createEditableDatabase {
// Check to see if editable database already exists
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *writableDB = [documentsDir stringByAppendingPathComponent:#"panberes.db"];
success = [fileManager fileExistsAtPath:writableDB];
// The editable database already exists
if (success) return;
// The editable database does not exist
// Copy the default DB to the application Documents directory.
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"panberes.db"];
success = [fileManager copyItemAtPath:defaultPath
toPath:writableDB error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file:'%#'.",
[error localizedDescription]);
}
}
i need some help
I believe the problem is after you create the database in the createDatabase method, you then close the database (sqlite_close(database)). You never reopen the database to perform the sqlite query. The method [self createEditableDatabase] only copies the editable database file if it doesn't exist in the first place, but it doesn't open the database. Sqlite will throw a "MISUSE" error whenever you attempt to run a query and there is no open database.
Also, it's unclear in your code if createDatabase and createEditableDatabase are dealing with the same database. If they are, it may be best to open the database and leave it open until you're done with it. Opening and closing a database multiple times will cause a performance penalty.

Resources