SQLite update statement not working - objective-c

HI I am using update statement for updating the record in sqlite database. Please help me what is the wrong in my code. i am not understanding where it is wrong. i am using the below code
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Notes.sqlite"];
sqlite3_stmt *updateStmt = nil;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = [[NSString stringWithFormat:#"update Notess Set Name=? Where NoteId = %#",_notesId] UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSLog(#"Error while creating update statement. %s", sqlite3_errmsg(database));
}else{
}
sqlite3_bind_text(updateStmt, 1, [textVew.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_finalize(updateStmt);
sqlite3_close(database);

You have failed to call sqlite3_step after your sqlite3_bind_text statement. Thus, you never actually performed the SQL.
Thus, it should look like:
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Notes.sqlite"];
sqlite3_stmt *updateStmt = nil;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = [[NSString stringWithFormat:#"update Notess Set Name=? Where NoteId = %#",_notesId] UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSLog(#"Error while creating update statement. %s", sqlite3_errmsg(database));
if (sqlite3_bind_text(updateStmt, 1, [textVew.text UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK)
NSLog(#"Error while binding value. %s", sqlite3_errmsg(database));
if (sqlite3_step(updateStmt) != SQLITE_DONE)
NSLog(#"Error during step. %s", sqlite3_errmsg(database));
sqlite3_finalize(updateStmt);
sqlite3_close(database);
}else{
NSLog(#"Error while opening database");
}

Related

Sqlite trying to retrieve a row doesn't work IOS 9

I'm saving an image in the document directory and then I save its path inside a SQLite DB. After the process finishes I try to retrieve the image path from the db but I can't get it working and I really have no Idea why. On the simulator the code works but on a real device it doesn't.
This is the code I've used to save the img path and to retrieve the img path and display the image inside an UIImageView
This is the code to save the image:
NSString *stringURL = #"http://addons.cdn.mozilla.net/user-media/addon_icons/80/80205-64.png?modified=1317416463";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *filePath;
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"test.png"];
[urlData writeToFile:filePath atomically:YES];
}
NSLog(#"path:%#",filePath);
[self saveImgPath:filePath];
This is the saveImgPath method:
-(void) saveImgPath:(NSString*)path{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &ImgDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO ImgPath (path) VALUES (\"%#\")",path];
const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare_v2(ImgDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_close(ImgDB);
}
[self performSegueWithIdentifier:#"sfondo" sender:self];
}
And this is how I retrieve it:
-(NSString*)getImgPath{
NSString* imgPath;
const char *dbpath = [[self GetDatabasePath] UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &ImgDB) == SQLITE_OK)
{
NSString *checkSQL = [NSString stringWithFormat: #"SELECT * FROM ImgPath"];
const char *insert_stmt = [checkSQL UTF8String];
sqlite3_prepare_v2(ImgDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_ERROR)
NSAssert1(0,#"Errore %s",sqlite3_errmsg(ImgDB));
else
sqlite3_step(statement);
sqlite3_finalize(statement);
sqlite3_close(ImgDB);
}
return imgPath;
}
The DB is initialized correctly and the NSLog of the paths are correct but I get 0 results when I try to retrieve the image path

I need to pass data from one view to another and retrieve that data on the second view

the first view is word list view controller and it has a word table containing word_id,word meaning and sentence and this data i need to pass on the other view having 1 text field which i add to display the word and two text views to display meaning and sentence.
Here is the code-
- (void)getListData
{
//tableData = [[NSMutableArray alloc]init];
sqlite3_stmt *statement;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"dexternotedb.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
WordListViewController *temp = APP_DELEGATE.wordListViewController;
NSLog(#"word id %ld",(long)[temp.wordId integerValue]);
NSString *sql=[NSString stringWithFormat:#"SELECT word_id, word ,meaning,sentence FROM words WHERE word_id=\"%#\"",APP_DELEGATE.wordListViewController.wordId];
const char *read_stmt = [sql UTF8String];
NSLog(#"select query%#",sql);
if(sqlite3_prepare_v2(database, read_stmt, -1, &statement, NULL) == SQLITE_OK){
//sqlite3_bind_int(statement, 1, [temp.wordId integerValue]);
while(sqlite3_step(statement) == SQLITE_ROW) {
NSString *word1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
word.text = word1;
NSString *meaning1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
meaning.text = meaning1;
NSString *sentence1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
Sentence.text = sentence1;
}
sqlite3_finalize(statement);
} else
{
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
}
}
Simply Store Value in NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:#"String" forKey:#"KeyName"];
[[NSUserDefaults standardUserDefaults] synchronize];
and whenever data is required fetch data from NSUserDefaults in entire app
NSString *str= [[NSUserDefaults standardUserDefaults] valueForKey:#"KeyName"];

Can't loop through sqlite statement using SQLITE_ROW Objective-C

I need to loop through a sqlite db but the function i'm using doesn't work at all,
this is the code i'm using:
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"CarrelloMese.sqlite"]];
NSUInteger helper;
helper = 0;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &Carrello) == SQLITE_OK) {
NSString *checkSQL = [NSString stringWithFormat: #"SELECT FROM CarrelloMese"];
const char *insert_stmt = [checkSQL UTF8String];
if(sqlite3_prepare_v2(Carrello, insert_stmt, -1, &statement, NULL)) {
while(sqlite3_step(statement) == SQLITE_ROW) {
[indexProdotti insertObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)] atIndex:helper];
}
}
sqlite3_finalize(statement);
sqlite3_close(Carrello);
}
When it reaches the While it doesn't enter, but I can't understand what's the problem.. The values are stored correctly on the DB (I checked with SqliteManager) and If I use a Count function within the app the count is correct, is there a problem with the code?
Your code seems to be correct. You forgot to add * in query.
Try this:
NSString *checkSQL = [NSString stringWithFormat: #"SELECT * FROM CarrelloMese"];

Table View is not reloaded after dismissing edit mode

I'm trying to add new row to TableView with edit mode. Used this tutorial. But after dismissing my edit mode view my table view is not reloaded. My addItem: method
- (IBAction)addItem:(id)sender {
BIDAppDelegate *appDelegate = (BIDAppDelegate *)[[UIApplication sharedApplication] delegate];
sqlite3 *database;
NSString *databaseName;
NSString *databasePath;
databaseName = #"TestProjectDatabase.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if(!success) {
databasePath = [[NSBundle mainBundle] pathForResource:databaseName ofType:nil];
}
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into \"MyItems\" ( \"MyItemName\", \"MyItemDescription\") values ( '%#', '%#');", _nameTextField.text, _descriptionTextField.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, insert_stmt, -1, &compiledStatement, NULL) != SQLITE_OK)
{
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}else{
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
// NSLog(#"All ok");
} else {
// NSLog(#"FAIL");
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
MyItems *itemsToDatabase = [[MyItems alloc] initWithItemName:_nameTextField.text andItemDescription:_descriptionTextField.text];
[appDelegate.myItems addObject:itemsToDatabase];
[self dismissModalViewControllerAnimated:YES];
}
SQL insertion is OK because where is new row after restarting my project. Any suggestions how to fix it?
Assuming the table data source reads from appDelegate.myItems, you just need to reload the table itself [tableView reloadData];.

My Update statement is not working

I tried to update an entry in my table like this:
NSFileManager *fileMgr=[NSFileManager defaultManager];
NSString *dbPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"quizDB.sqlite"];
if ([fileMgr fileExistsAtPath:dbPath]) {
NSLog(#"DB does exist!");//displayed
}
const char *dbpath = [dbPath UTF8String];
sqlite3_stmt *updateStmt;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"%i",id_quiz);//displayed, in a test case it display 1 which is a quiz ID in the table
NSString *querySql=[NSString stringWithFormat:#"Update quiz set etat=1 where id=\"%i\"",id_quiz];
const char*sql=[querySql UTF8String];
sqlite3_prepare_v2(contactDB, sql, -1, &updateStmt, NULL);
if(SQLITE_DONE != sqlite3_step(updateStmt))
{
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(contactDB));
}
else{
sqlite3_reset(updateStmt);
NSLog(#"Update done successfully!");//this is also displayed, i guess everything is ok then and the entry is updated
}
sqlite3_finalize(updateStmt);
sqlite3_close(contactDB);
}
In the log, i got the message: Update done successfully! so i assumed that everything is, however when i check the database within SQLite Manager in Mozilla Firefox, the entry is not updated. Am i missing something? thanx for help
first copy your database from resource to document dir:
- (void) checkAndCreateDatabase
{
NSString *database_Name =#"quizDB.sqlite"
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *database_Path = [documentsDir stringByAppendingPathComponent:database_Name];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:database_Path])
{
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:database_Name];
[fileManager removeItemAtPath:database_Path error:nil];
[fileManager copyItemAtPath:databasePathFromApp toPath:database_Path error:nil];
}
else
{
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:database_Name];
[fileManager copyItemAtPath:databasePathFromApp toPath:database_Path error:nil];
}
}
and after you update your database:
- (void) UpdateDatabase
{
sqlite3 *contactDB;
sqlite3_stmt *updateStmt;
NSString *database_Name =#"quizDB.sqlite"
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *dbpath = [documentsDir stringByAppendingPathComponent:database_Name];
if(sqlite3_open([dbpath UTF8String], &contactDB) == SQLITE_OK)
{
NSString *querySql=[NSString stringWithFormat:#"Update quiz set etat=1 where id=\"%i\"",id_quiz];
const char*sql=[querySql UTF8String];
if(sqlite3_prepare_v2(contactDB,sql, -1, &updateStmt, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(updateStmt))
{
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(contactDB));
}
else{
sqlite3_reset(updateStmt);
NSLog(#"Update done successfully!");
}
}
sqlite3_finalize(updateStmt);
}
sqlite3_close(contactDB);
}
and check your database which save in documentdir not in resource