Display multiple images from database - iphone

I created local database for storing multiple images. I stored this file to Mainbundle. When i fetch the data only one image will be displaying from database. But i need to display all images under scrollview.
code:
NSMutableArray *appArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"App4.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured.");
}
const char *sql = "SELECT * FROM App4Tbl";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Myapp *Mylist = [[Myapp alloc]init];
Mylist.appId = sqlite3_column_int(sqlStatement, 0);
Mylist.app = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
Mylist.rating = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
const char *raw = sqlite3_column_blob(sqlStatement, 3);
int rawLen = sqlite3_column_bytes(sqlStatement, 3);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
Mylist.photo = [[UIImage alloc] initWithData:data];
[appArray addObject:Mylist];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return appArray;
}

Related

sqlite3_prepare_v2() == SQLITE_OK returns NO and existing table is not found

I am developing an iphone application which using sqlite3 database file. and i am using following code to select from sqlite3 database ;
NSString* dbYolu = [NSString stringWithFormat:#"%#/emhdb3.sqlite3",NSHomeDirectory()];
sqlite3* db;
NSLog(#"%# dbyolu : ", dbYolu);
if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat: #"SELECT username, mobile FROM peopleto WHERE namesurname=\"%#\"", name.text];
NSLog(#"%# : query", query);
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK) // statement stmt returns null and returns SQLITE_OK = FALSE.
{
NSLog(#"stepped in SQLITE_OK is TRUE");
while (sqlite3_step(stmt) == SQLITE_ROW)
{
NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
double not = sqlite3_column_double(stmt, 1);
NSLog(#"%# : %f", ders_kodu, not);
}
}
else
{
NSLog(#"%# - but failed", stmt);
}
sqlite3_finalize(stmt);
}
else
NSLog(#"db could not be opened");
it fails at the "sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK" point above. and the error is : "Error:No such table : peopleto. But it successfully returns the content of table when i run this query in sql browser. I mean this query is correct and working.
btw, I get the file with pathname with the following code on viewLoad
- (void)viewDidLoad
{
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: #"emhdb3.sqlite3"]];
NSLog(#"dbpath : %#", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(#"db not found");
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"SQLITE_OK is passed");
//.... some codes here, doesn't metter for me because SQLITE_OK = true
} else {
status.text = #"Failed to open/create database";
}
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"i found the file here : %s",[databasePath UTF8String]);
}
NSLog(#"completed");
[super viewDidLoad];
}
I have the database file in my project folder and added to the project.
What i am missing?
Thanks
///////
i am sorry for updating my question but stackoverflow does not allow me to add new ,
please find my update below ;
Here is the updated version of the code :
viewLoad part;
- (void)viewDidLoad
{
[self createEditableCopyOfDatabaseIfNeeded];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"emhdb3.sqlite3"]];
NSLog(#"dbpath : %#", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS peopleto (pId INTEGER PRIMARY KEY AUTOINCREMENT, namesurname TEXT, mobile TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
} else {
status.text = #"Failed to open/create database";
}
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"%s is filepath",[databasePath UTF8String]);
}
NSLog(#"checkpoint 4");
[super viewDidLoad];
}
buraya başka birşey yaz
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(#"entered createEditableCopyOfDatabaseIfNeeded");
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"emhdb3.sqlite3"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
{
NSLog(#"success == YES returned");
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"emhdb3.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog( #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
else{
NSLog(#"checkpoint 2");
}
}
and the part that select query is performed ;
-(IBAction)findcontact2:(id)sender
{
NSString *dbYolu = databasePath;
sqlite3* db;
NSLog(#"%# dbyolu : ", dbYolu);
if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat: #"SELECT namesurname, mobile FROM peopleto"]; //any query
NSLog(#"%# : query", query);
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK)
{
NSLog(#"SQLITE is OK");
while (sqlite3_step(stmt) == SQLITE_ROW)
{
NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
double not = sqlite3_column_double(stmt, 1);
NSLog(#"%# : %f", namesurname, mobile);
}
}
else
{
NSLog(#"Error=%s",sqlite3_errmsg(db)); // error message : Error=no such table: peopleto
NSLog(#"%# - is stmt", stmt); //stmt is null
}
sqlite3_finalize(stmt);
}
else
NSLog(#"could not open the db");
}
As i pointed above, the error is Error=no such table: peopleto and stmt is returned null
Are you copying your SQL file to documents, if not you need to do that first. While adding SQL file to project, it is added in your bundle and not in documents directory. YOu need to copy that first
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"bookdb.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"bookdb.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog( #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Please check the DB which is in your main bundle contains the table then try to copy it to resource folder and apply the above

sqlite3_prepare error #26

I have following code (modified code from this tutorial):
-(NSMutableArray *) getChampionDatabase
{
NSMutableArray *championsArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *databasePath = [[NSBundle mainBundle]pathForResource: #"Champions Database" ofType:#"sqlite"];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if (!success)
{
NSLog(#"cannot connect to Database! at filepath %#",databasePath);
}
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "SELECT CHAMPION_ID,CHAMPION_NAME,CHAMPION_IMG FROM CHAMPIONS";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(database, sql, -1, &sqlStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
championList *ChampionList = [[championList alloc]init];
ChampionList.championId = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)];
ChampionList.championName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
ChampionList.championImage = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
[championsArray addObject:ChampionList];
}
}
else
{
NSLog(#"problem with database prepare");
}
}
else
{
NSLog(#"problem with database openning");
}
}
#catch (NSException *exception)
{
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally
{
return championsArray;
}
}
After running this code i always have output : "problem with database prepare"
Then i tried to check error number of sqlite3_prepare by following code:
int ret = sqlite3_prepare(database, sql, -1, &sqlStatement, NULL);
if (ret != SQLITE_OK) {
NSLog(#"Error calling sqlite3_prepare: %d", ret);
}
output: "Error calling sqlite3_prepare: 26"
error 26 - /*File opened that is not a database file */
File have sqlite 3 version
how is this possible? file extension is .sqlite and i can modify it in sqlite manager
Make sure you added your DB to the ressource bundle of your project and don't put any space in your name of your DB. For example use a name like champion_db.sqlite.

how to insert values in sqlite

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath =[documentsDir stringByAppendingPathComponent:#"register.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
sqlite3_stmt *selectstmt;
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"register.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
sql = "select lastname,email,firstname from reg_FORM";
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
lastname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
email=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
firstname=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
NSLog(#"----%#",lastname);
NSLog(#"----%#",email);
NSLog(#"----%#",firstname);
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
}
I am using this code to retrieve the values in db, but I did know how to insert data in db. I am trying this below code but it does not work
const char *sql = "insert into reg_FORM (firstname,lastname,email,company,phone) VALUES (aaa,aaa,aaa,aaaa,1223)";
sqlite3_exec(database, [[NSString stringWithFormat:#"insert into reg_FORM (firstname,lastname,email,company,phone) VALUES (aaa,aaa,aaa,aaaa,1223)"] UTF8String], NULL, NULL, NULL);
//give code for insert values in db
{
BOOL returnValue = YES;
sqlite3_stmt *insertStmt = nil;
sqlite3 *UserDB ;
if (sqlite3_config(SQLITE_CONFIG_SERIALIZED) == SQLITE_OK)
{
NSLog(#"Can now use sqlite on multiple threads, using the same connection");
}
int ret = sqlite3_enable_shared_cache(1);
if(ret != SQLITE_OK)
{
}
// Open the database. The database was prepared outside the application.
if (sqlite3_open([app.dataBasePath UTF8String], &UserDB) == SQLITE_OK)
{
if(insertStmt == nil)
{
NSString *strValue = [NSString stringWithFormat:#"insert into languagemaster Values(?,?)"];
const char *sql = [strValue UTF8String];
if(sqlite3_prepare_v2(UserDB, sql, -1, &insertStmt, NULL) != SQLITE_OK)
{
NSLog(#"Error while creating insertStmt in tblUserAccount %#", [NSString stringWithUTF8String:(char *)sqlite3_errmsg(UserDB)]);
returnValue = NO;
}
}
if(sqlite3_bind_int(insertStmt, 1, langid) ) // langid is int
{
return NO;
}
if(sqlite3_bind_text(insertStmt, 2, [strLanguageName UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) // strLanguageName is string
{
return NO;
}
if(SQLITE_DONE != sqlite3_step(insertStmt))
{
NSLog(#"Error while Executing insertStmt in tblLocation %#", [NSString stringWithUTF8String:(char *)sqlite3_errmsg(UserDB)]);
returnValue = NO;
}
sqlite3_reset(insertStmt);
if (insertStmt)
{
sqlite3_finalize(insertStmt);
insertStmt = nil;
}
}
sqlite3_close(UserDB);
return returnValue;
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath =[documentsDir stringByAppendingPathComponent:#"register.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
sqlite3_stmt *selectstmt;
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"register.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "insert into reg_FORM (firstname,lastname,email,company,phone) VALUES ('sdcbb','bbbb','bbbb','bbbb',1111122)";
sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL);
if(sqlite3_step(selectstmt)==SQLITE_DONE)
{
NSLog(#"insert successfully");
}
else
{
NSLog(#"insert not successfully");
}
sqlite3_finalize(selectstmt);
sqlite3_close(database);
}

Unable to update database

I'm having trouble updating my database. I believe it's due to it possibly being read only, however I am unsure. I created my database in my console, and the code below adds the database to the project folder rather than referencing it externally. Here is the code to transfer the file to the project folder
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
databaseName = #"databasenew.sql";
/* copy over to phone code */
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:#"databasenew.sql"];
if (![[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (error) {
NSLog(#"Could not copy json file: %#", error);
}
else{
NSLog(#"yea");
}
}
else{
NSLog(#"transfer complete");
}
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Here is the code where I try to update
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
NSLog(soapResults);
NSString *convertString = soapResults;
check = [convertString intValue];
NSLog(#"user is");
NSLog(user);
if(check > 0){
databaseName = #"databasenew.sql";
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "UPDATE people set user = 'munch'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"success");
NSLog(soapResults);
BOOL success = sqlite3_step(compiledStatement);
if (success != SQLITE_DONE) {
BOOL myBool=YES;
NSLog([NSString stringWithFormat:#"My Bool value : %d",success]);
}
}else{
NSLog(#"the fail ispreparing something");
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}else{
NSLog(#"fail");
}
sqlite3_close(database);
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
[self Bootup];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
I've done my NDlog debugging and it says "success" as it should if the code for updating is successful, however the database itself does not update. What is the reason for this?
You are forgeting some code for update statement
//the binding part is missing in your code , you need to write after Prepare statement.
sqlite3_bind_text(compiledStatement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(compiledStatement);
Via iphonesdkarticles.com.
This will resolve your error.
-(BOOL) someUpdateFunction {
BOOL updatedSuccessfully = NO;
// Open the database.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *updateQuery = [[NSString alloc] initWithFormat:#"UPDATE people SET user = 'terror' WHERE user = 'greg'"];
const char *query = [updateQuery UTF8String];
[updateQuery release];
sqlite3_stmt *statement;
int res = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
if(res == SQLITE_OK) {
int result = sqlite3_step(statement);
if(result == SQLITE_DONE) {
updatedSuccessfully = YES;
sqlite3_finalize(statement);
}else {
NSLog(#"Failed with error code: %d", result);
}
}else {
NSLog(#"Failed to prepare the update query with error code: %d", res);
}
}else {
NSLog(#"Failed to open the database");
}
sqlite3_close(database);
//NSLog(updatedSuccessfully);
//NSLog(#"The value of the bool is %#\n", updatedSuccessfully);
return updatedSuccessfully;
}
I was supplied this in the chat room. Thanks lads.
Remember to copy the DB over to the device else. You can find the DB path with this code:
- (NSString *) dataFilePath:(NSString *) dbName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
return dbPath;
}
-(BOOL)buildtheDB{
BOOL updatedSuccessfully = NO;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile] == NO) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"database" ofType:#"sqlite"];
NSError *error = nil;
BOOL databaseCopied = [[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (databaseCopied == NO) {
if (error) {
NSLog(#"Could not copy database file with error: %#", [error localizedDescription]);
}
}else {
NSLog(#"Database copied successfully");
}
}
else{
NSLog(#"Database already copied");
}
return updatedSuccessfully;
}

Update statement not working properly [duplicate]

I'm having trouble updating my database. I believe it's due to it possibly being read only, however I am unsure. I created my database in my console, and the code below adds the database to the project folder rather than referencing it externally. Here is the code to transfer the file to the project folder
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
databaseName = #"databasenew.sql";
/* copy over to phone code */
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:#"databasenew.sql"];
if (![[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (error) {
NSLog(#"Could not copy json file: %#", error);
}
else{
NSLog(#"yea");
}
}
else{
NSLog(#"transfer complete");
}
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Here is the code where I try to update
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
NSLog(soapResults);
NSString *convertString = soapResults;
check = [convertString intValue];
NSLog(#"user is");
NSLog(user);
if(check > 0){
databaseName = #"databasenew.sql";
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "UPDATE people set user = 'munch'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"success");
NSLog(soapResults);
BOOL success = sqlite3_step(compiledStatement);
if (success != SQLITE_DONE) {
BOOL myBool=YES;
NSLog([NSString stringWithFormat:#"My Bool value : %d",success]);
}
}else{
NSLog(#"the fail ispreparing something");
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}else{
NSLog(#"fail");
}
sqlite3_close(database);
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
[self Bootup];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
I've done my NDlog debugging and it says "success" as it should if the code for updating is successful, however the database itself does not update. What is the reason for this?
You are forgeting some code for update statement
//the binding part is missing in your code , you need to write after Prepare statement.
sqlite3_bind_text(compiledStatement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(compiledStatement);
Via iphonesdkarticles.com.
This will resolve your error.
-(BOOL) someUpdateFunction {
BOOL updatedSuccessfully = NO;
// Open the database.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *updateQuery = [[NSString alloc] initWithFormat:#"UPDATE people SET user = 'terror' WHERE user = 'greg'"];
const char *query = [updateQuery UTF8String];
[updateQuery release];
sqlite3_stmt *statement;
int res = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
if(res == SQLITE_OK) {
int result = sqlite3_step(statement);
if(result == SQLITE_DONE) {
updatedSuccessfully = YES;
sqlite3_finalize(statement);
}else {
NSLog(#"Failed with error code: %d", result);
}
}else {
NSLog(#"Failed to prepare the update query with error code: %d", res);
}
}else {
NSLog(#"Failed to open the database");
}
sqlite3_close(database);
//NSLog(updatedSuccessfully);
//NSLog(#"The value of the bool is %#\n", updatedSuccessfully);
return updatedSuccessfully;
}
I was supplied this in the chat room. Thanks lads.
Remember to copy the DB over to the device else. You can find the DB path with this code:
- (NSString *) dataFilePath:(NSString *) dbName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
return dbPath;
}
-(BOOL)buildtheDB{
BOOL updatedSuccessfully = NO;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile] == NO) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"database" ofType:#"sqlite"];
NSError *error = nil;
BOOL databaseCopied = [[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (databaseCopied == NO) {
if (error) {
NSLog(#"Could not copy database file with error: %#", [error localizedDescription]);
}
}else {
NSLog(#"Database copied successfully");
}
}
else{
NSLog(#"Database already copied");
}
return updatedSuccessfully;
}