Not getting the output when trying the data from the sqlite database - iphone

I am new to Objective - C and Sqlite database.So I don't understand what is the mistake in my code. I am doing a simple Todo List. In the first page, I want to display all the tasks and in the header, there is one add button.When we click on that button, it will move to the second storyboard.In that, we can enter the main task and subtask. I have created a new page named TodolistView1Controller and in that I have created the database and inserted the data into the db. But my problem is When we come back to the main page, it will not show the new task which we entered now. I will paste the code below :-
In TodolistView1Controller.m
-(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: #"todo.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS TODO (ID INTEGER PRIMARY KEY AUTOINCREMENT, MYTASK TEXT, SUBTASK TEXT)";
if (sqlite3_exec(todoDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
status.text = #"Failed to create table";
}
status.text = #"Created the database";
sqlite3_close(todoDB);
} else {
status.text = #"Failed to open/create database";
}
} - (IBAction)save:(id)sender {
[myTask resignFirstResponder];
[subTask resignFirstResponder];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO TODO (MYTASK, SUBTASK) VALUES (\"%#\", \"%#\")", myTask.text, subTask.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(todoDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status.text = #"Contact added";
myTask.text = #"";
subTask.text = #"";
} else {
status.text = #"Failed to add contact";
}
NSLog(#"7");
sqlite3_finalize(statement);
sqlite3_close(todoDB);
}
And in Main ViewController.m
-(void)viewDidLoad
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"Display1");
if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
{
NSLog(#"Display2");
NSString *querySQL = [NSString stringWithFormat:
#"SELECT MYTASK, SUBTASK FROM TODO "];
NSLog(#"Display3");
const char *query_stmt = [querySQL UTF8String];
NSLog(#"Display4");
if (sqlite3_prepare_v2(todoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"Display5");
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"Display6");
NSLog(#"Data is displayed");
} else {
NSLog(#"Display7");
NSLog(#"Data cannot be displayed");
}
sqlite3_finalize(statement);
}
sqlite3_close(todoDB);
}
So whenever i run this, I am getting the output Display1, Display2, Display3 and Display4 in the console . Can anyone please tell me why i am not getting the output display5 and display6.
Thanks in advance.

When you first displayed your list of to-do task, they are rendered to screen.
Subsequent inserts into the database are stored into the database but you have not yet told the app to re-fetch the list of to-do task from the database when you returned to your main page.
In the "viewWillAppear" or "viewDidAppear" of your to-do list page, write a method to fetch all your to do list. Make sure when you fetch the records, you store them in your array which you will use to render them into the table view.
Then after you have fetched your list of to-do from the SQL database, execute this method
[myTableView reloadData];
That will essentially reload your table and display any new records which are contained in your array of to-do.

Related

Prepare-error : no such table: items

this function is showing me the error that "Prepare-error #0: no such table: items
". can some one please help me out in resolving this error.
- (void)viewDidLoad
{
[super viewDidLoad];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB)== SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"Select name FROM items"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{ NSLog(#"Data not fetched");
if (sqlite3_step(statement) == SQLITE_ROW)
{NSLog(#"Prepare-error #%i: %s", (sqlite3_prepare_v2(contactDB, [querySQL UTF8String], -1, &statement, NULL) == SQLITE_OK), sqlite3_errmsg(contactDB));
NSString *namefeild = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[list objectAtIndex:namefeild];
}
else{
NSLog(#"Data not fetched");
}
sqlite3_finalize(statement);
}else {NSLog(#"Prepare-error #%i: %s", (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK), sqlite3_errmsg(contactDB));}
sqlite3_close(contactDB);
}
These two functions are n different viewcontrollers.
In view didload the database is created.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPath;
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"contactDB"]];
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 items(name varchar, price integer, description varchar)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Fail to create table");
}
sqlite3_close(contactDB);
}else{
NSLog(#"Failed to open database");
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
and in save action the data is added to the database.
- (IBAction)save:(id)sender {
sqlite3_stmt *statement;
const char *dbpath = [ databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:#"insert into items(name, price, description) values (\"%#\",\"%#\",\"%#\")", nametxt.text, pricetxt.text, description.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"contact added");
nametxt.text= #"";
pricetxt.text = #"";
description.text = #"";
}else{
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
const char *dbpath = [databasePath UTF8String];
NSLog("%#", databasePath);
...
...
}
Copy the database path to your clipboard and paste it into your console.
cd "[database path]"
sqlite3 database_filename.db
.dump
After the .dump command, do you see the creation statement for your table? If not, then you need to double check the location of where you are actually creating your database. It would actually be very helpful if you updated your answer with the contents of the .dump command.
Typically this means that the table does not exist in the database you opened. You should find the database in your simulator's Documents folder (~/Library/Application Support/iPhone Simulator) and, open it in your MacOS SQLite tool of choice, see for yourself whether the table is there. I suspect it will not be there.
A common source of this problem is for a file at the databasePath to not exist (e.g. you might have copy of database in the bundle, but not the Documents folder), in which case sqlite3_open will quietly create a new, blank database at databasePath.
Assuming you don't want it to create a blank database when it doesn't find it, you should:
Remove your app from the simulator/device (so that any blank databases are removed);
Check your original opening routine and use NSFileManager to check for the existence of the database if it's not already there (perhaps copying the database from the bundle to documents before continuing);
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:databasePath]) {
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"itemsdb" ofType:#"sqlite"];
[fileManager copyItemAtPath:bundlePath toPath:databasePath error:nil];
}
Or perhaps your code should dynamically create the table(s) if the database didn't exist, but the idea is the same. Check for existence of the file before opening it.
Perhaps in the future, consider using sqlite3_open_v2 with the SQLITE_OPEN_READWRITE option (but not the SQLITE_OPEN_CREATE option), which will not create the database for you and will report an error if the database was not found.
Having said the above (which is the general counsel when someone encounters an error like yours, where the table that you know "should" be there, isn't), there are specific issues unique to your code sample in the way you handle error reporting:
If step succeeds, you're reporting an error. Surely you meant to only do that if step failed.
The error you generate as a result of step says "prepare error". Surely that should be "step error".
Your logging of errors is calling the function that failed again in order to get the return code. You should save the return code when you first called the function, saving you from having to call it again for your error message. (This is important because sometimes the value returned by the function will change and reset your error message. Don't call the failed function again!) It's also more efficient to just save the original return code.
Thus:
if (sqlite3_open(dbpath, &contactDB)== SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"Select name FROM items"];
const char *query_stmt = [querySQL UTF8String];
int rc; // variable to hold the return code
if ((rc = sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL)) == SQLITE_OK)
{
if ((rc = sqlite3_step(statement)) == SQLITE_ROW)
{
NSString *namefeild = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[list objectAtIndex:namefeild];
}
else {
if (rc == SQLITE_DONE)
NSLog(#"step found no data");
else
NSLog(#"step-error #%i: %s", rc, sqlite3_errmsg(contactDB));
}
sqlite3_finalize(statement);
} else {
NSLog(#"Prepare-error #%i: %s", rc, sqlite3_errmsg(contactDB));
}
sqlite3_close(contactDB);
}

SQLite Database table never created

I'm trying to create a SQLite Database but run into a problem that seems to derive from the table CONTACTS never being created (I get the error message 'Error while inserting 'no such table: CONTACTS'
').
From the code below, can anyone see what is wrong and how it can be corrected? This example is taken straight from this guide, which is why I'm surprised it doesn't work:
http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_6_iPhone_Application
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
//Buid the path for database file
_databasePath = [[NSString alloc]
initWithString:[docsDir stringByAppendingPathComponent:#"contacts.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *db_path = [_databasePath UTF8String];
if(sqlite3_open(db_path, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
_text.text = #"Failed to create table";
}
sqlite3_close(_contactDB);
} else {
_text.text = #"Failed to open/create database";
}
}
}
- (IBAction)saveName:(id)sender {
NSString *currentName = self.text.text;
NSString *nameSaved = [[NSString alloc] initWithFormat:currentName];
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSLog(#"pass");
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO CONTACTS (name) VALUES (\"%#\")",
nameSaved];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"pass");
} else {
NSLog( #"Error while inserting '%s'", sqlite3_errmsg(_contactDB));
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
There is nothing wrong with that code - it runs fine here on Mac OS X and in the iOS simulator. Does the error come later when you try and insert data into the table? Are you closing the file before trying to insert data into it?
Run it in the simulator, step through the code, and then find the file in the simulator's Documents directory. Use Terminal to see what's in the file:
sqlite3 path-to-file .dump
The exact path will differ on your machine but in my iOS simulator I get:
sqlite3 "/Users/my-login-name/Library/Application Support/iPhone Simulator/6.1/Applications/DAD0BB47-2136-4367-8DAF-AA578D0C00A5/Documents/contacts.db" .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT);
COMMIT;
You can see that the table exists with the correct columns.
Use objectAtIndex:
sqlite3* _contactDB;
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
//Buid the path for database file
NSString * _databasePath = [[NSString alloc]
initWithString:[docsDir stringByAppendingPathComponent:#"contacts.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *db_path = [_databasePath UTF8String];
if(sqlite3_open(db_path, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table") ;
}
sqlite3_close(_contactDB);
} else {
NSLog( #"Failed to open/create database");
}
}

Unable to remove data from database ios

I have database, but when i tried to remove data from the database nothing happens, what should i do to make sure it works? Because when i pressed delete the dta is still in the database
This is the code:
/file path to database
-(NSString*)filePath {
NSArray*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[paths objectAtIndex:0]stringByAppendingPathComponent:#"bp.sql"];
}
//open database
-(void)openDB {
if(sqlite3_open([[self filePath]UTF8String], &db) !=SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Databese failed to open");
}
else {
NSLog(#"database opemed");
}
}
- (IBAction)del:(id)sender {
NSString*sql = [NSString stringWithFormat:#"DELETE key, theDate, customer, code1, code2 FROM summary WHERE key=\"%#\"",customerName];
const char* query_stmt = [sql UTF8String];
sqlite3_stmt*statement;
sqlite3_prepare_v2(db, query_stmt, -1, & statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSAssert(0, #"database object delete failed");
} else {
NSLog(#"No error");
}
sqlite3_finalize(statement);
sqlite3_close(db)
You can't delete specific column values using the DELETE query. It's for removing the entire row.
The problem is with the following query:
NSString*sql = [NSString stringWithFormat:#"DELETE key, theDate, customer, code1, code2 FROM summary WHERE key=\"%#\"",customerName];
Change it to:
NSString*sql = [NSString stringWithFormat:#"DELETE FROM summary WHERE key=\"%#\"",customerName];
If you need to remove particular column value of a row use the UPDATE query.
Please check the sqlite documentation for the details
All the functions that you wrote like checking filepath, opendb should occur in the same function(maybe inside your del function).
This is how I will do it:
-(void)updateStatus:(NSString *)queryString {
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
strDatabasePath = [NSString stringWithString:[docsDir stringByAppendingPathComponent:#"bp.sql"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: strDatabasePath] == YES)
{
const char *dbpath = [strDatabasePath UTF8String];
if (sqlite3_open(dbpath, &sqlDatabase) == SQLITE_OK)
{
const char* beginString = "BEGIN;";
sqlite3_stmt *compiledstatement;
sqlite3_prepare_v2(sqlDatabase, beginString, -1, &compiledstatement, NULL);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else DLog(#"Failed!");
sqlite3_finalize(compiledstatement);
DLog(#"QUERY : %#",queryString);
const char *selectStatement = [queryString UTF8String];
sqlite3_prepare_v2(sqlDatabase, selectStatement, -1, &compiledstatement, NULL);
//sqlite3_bind_text(compiledstatement,1,[statusString UTF8String],-1,SQLITE_TRANSIENT);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else DLog(#"Failed!");
sqlite3_finalize(compiledstatement);
const char* endString="END;";
sqlite3_prepare_v2(sqlDatabase, endString, -1, &compiledstatement, NULL);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else DLog(#"Failed!");
sqlite3_finalize(compiledstatement);
sqlite3_close(sqlDatabase);
}
else DLog(#"Failed to open table");
}
}
NSString *queryString;
queryString = [NSString stringWithFormat:#"DELETE key, theDate, customer, code1, code2 FROM summary WHERE key=\"%#\"",customerName];
[self updateStatus:queryString];
Hope this helps...
-(BOOL)DeleteWishList:(int)rowno
{
NSString *queryString=[NSString stringWithFormat:#"delete from wishtable where _id=%d",rowno];
[self openDB];
char *err;
if (sqlite3_exec(dBObject, [queryString UTF8String], NULL,NULL, &err)!= SQLITE_OK)
{
sqlite3_close(dBObject);
return NO;
}
else
{
return YES;
}
}

Getting error while executing SQLite command from application

I have this simple function in my application :
-(NSMutableArray *)SelectProductID:(NSMutableArray *)arr
{
NSLog(#"----------------");
sqlite3_stmt *statement;
NSMutableArray *arrPordID = [[NSMutableArray alloc]init];
#try
{
//Get productID
for(NSString *strSubProductID in arr)
{
NSString *s = [NSString stringWithFormat:#"SELECT ProductID FROM SubProducttable where SubProductID=%#",strSubProductID];
const char *sql = [s cStringUsingEncoding:NSASCIIStringEncoding];
if (sqlite3_prepare_v2(database, [s cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW){
char *dbString;
dbString = (char *)sqlite3_column_text(statement, 0);
NSString *pID = (dbString) ? [NSString stringWithUTF8String:dbString] : #"";
[arrPordID addObject:pID];
}
}
}
}
#catch (NSException *exception) {
#throw exception;
}
#finally {
sqlite3_finalize(statement);
}
return arrPordID;
}
I am encountering a strange problem here. When application reaches while (sqlite3_step(statement) == SQLITE_ROW){, loop is never entered. I don't know why. I executed the same query in SQLite manager (when application is not running). And I get result as a single one. The result I get is 2. But here I am getting nothing.
And yes, I always close the database in SQLite manager whenever I run my application. I have also cleaned the application, restarted XCode, and removed the application from simulator. But no success.
Also I saw a strange thing during debugging. While debugging, sqlite3_stmt *statement is always skipped. Is this the reason I am not getting any result?
Have you tried subproductId in single quotes?
NSString *s = [NSString stringWithFormat:#"SELECT ProductID FROM SubProducttable where SubProductID='%#'",strSubProductID];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlQuery = #"SELECT ProductID FROM SubProducttable where SubProductID=%#",strSubProductID;
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database, statement, -1, &sqlQuery, NULL) == SQLITE_OK) {
while(sqlite3_step(sqlQuery ) == SQLITE_ROW) {
// Read the data and add to your array object
}
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
}
sqlite3_close(database)

Problems storing data in iPhone SQLite help!

I just started looking into SQLite for the iPhone SDK. I have been looking at this tutorial and I am wondering how can I find an ID and store the information in that field of the ID? (the tutorial increments an ID every time I press save).
Also, how can I loop though the whole database e.g., add all the id numbers up? Is there a command?
Not much changes in the database access in the methods. Only the SQLite query changes. It should be something on these lines.
- (NSInteger) sumOfIds
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSString *result;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = #"SELECT sum(id) FROM contacts";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *result = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
return [result floatValue];
}