SQLite pathway iOS - ios

I'm trying to access to my table in my SQLite using this code :
fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"movieData.sqlite"];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK){
const char *sql = "SELECT movieName FROM myMovies";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
My output is "Problem with prepare statement". I'm pretty sure about my table name and other things in the *sql. But still doesn't work. any idea guys ?!

added
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.");
}
just before cont char *sql and it's working now :)

Related

Update query run without error but do not update database ios sqlite objective C

I am running SQLite query on my database. The select query is working fine, but when I am running SQLite query no error is generated, but it is still not updating my database values.
The function is as follows :
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"bikeapp.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.");
}
NSString *query = [NSString stringWithFormat:#"UPDATE bikes SET to_show = 0 where id = %ld",(long)bikeId];
//const char *sql = "UPDATE bikes SET to_show = 0 where id = 3";
const char *sql = [query UTF8String];
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
if(sqlite3_step(sqlStatement))
{
return YES;
}else
return NO;
//
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
The code runs through without any error or exception but it is not updating the values inside the database. The query when run directly on database shows the changes being done. If anybody can help me out here I would appreciate it. Thanks.

iOS - Error connecting to db on real device

I have been working on an Ionic Phonegap project for iOS. There is a method implemented in Appdelegate.m which makes an AJAX request to download a text file from a server, which contains a URL to connect to another server in order for the app to work.
I have made two classes,
WebContent and WebCustomContent
In WebContent.m I insert a particular URL taken from the text file to a sqlite DB and then retrieve it using WebCustomContent.m
Refer to the following code block
-(NSString*)getDataBasePath{
//CHECK
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:#"webcontentdb.sqlite"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
NSLog(#"%d", fileExists);
//END OF CHECK
//SIMULATOR
NSString *databasePath1 = [[NSBundle mainBundle] pathForResource:#"webcontentdb" ofType:#"sqlite"];
// return databasePath1;
//REAL DEVICE
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* databasePath = [documentsDirectory stringByAppendingPathComponent:#"webcontentdb.sqlite"];
return databasePath;
}
-(void)updateUserAgeRange:(NSString*)age{
NSString* databasePath = [self getDataBasePath];
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *query = [NSString stringWithFormat:#"update user_setting set valstr = '%#' where keystr = 'AGE' ", age];
NSLog(#"update %#" , query);
const char * sql = [query UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(_database, sql, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_step(compiledStatement); // Here is the added step.
NSLog(#"updateContact SUCCESS - executed command %#",query);
}
else {
NSLog(#"updateContact FAILED - failed to execute command %#",query);
}
sqlite3_finalize(compiledStatement);
}
else {
//NSLog(#"pdateContact FAILED - failed to open database");
}
sqlite3_close(database);
}
- (NSString *)getUserPreferenceValues:(NSString*)keystr {
NSString *retval = [[NSString alloc] init] ;
NSString *query = [NSString stringWithFormat:#"SELECT valstr FROM user_setting where keystr = '%#' " , keystr];
NSLog(#" query %#", query);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
char *nameChars = (char *) sqlite3_column_text(statement, 0 );
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
NSLog(#" valstr %#", name);
retval = name;
}
sqlite3_finalize(statement);
}
return retval;
}
-(void)insertDatabaseCommonValues:(NSString*)urlstr{
NSString* databasePath = [self getDataBasePath];
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *query = [NSString stringWithFormat:#"delete from url_preference"];
const char * sql = [query UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(_database, sql, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_step(compiledStatement); // Here is the added step.
// NSLog(#"updateContact SUCCESS - executed command %#",query);
}
else {
//NSLog(#"updateContact FAILED - failed to execute command %#",query);
}
sqlite3_finalize(compiledStatement);
}
else {
//NSLog(#"pdateContact FAILED - failed to open database");
}
//************************************INSERT************************************//
//sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
//NSLog(#"URL STRING %#",urlstr);
NSString *query = [NSString stringWithFormat:#"insert into url_preference (name) values ( '%#' ) ", urlstr];
NSLog(#"inset %#" , query);
const char * sql = [query UTF8String];
sqlite3_stmt *compiledStatement;
NSLog(#" error code.. %d",sqlite3_prepare_v2(_database, sql, -1, &compiledStatement, NULL));
if(sqlite3_prepare_v2(_database, sql, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_step(compiledStatement); // Here is the added step.
NSLog(#"updateContact SUCCESS - executed command %#",query);
}
else {
NSLog(#"updateContact FAILED - failed to execute command %#",query);
}
sqlite3_finalize(compiledStatement);
}
else {
//NSLog(#"pdateContact FAILED - failed to open database");
}
sqlite3_close(database);
}
Here, when I print the BOOL variable fileExists, it prints YES, meaning the database exists in Documents folder.
But insertion and update queries fail as follows;
2015-06-22 11:18:18.215 App Name[5510:60b] URL http://www.google.lk
2015-06-22 11:18:22.082 App Name[5510:60b] 1
2015-06-22 11:18:24.103 App Name[5510:60b] success to open database!
2015-06-22 11:18:26.197 App Name[5510:60b] 1
2015-06-22 11:18:28.673 App Name[5510:60b] inset insert into url_preference (name) values ( 'http://www.google.lk' )
2015-06-22 11:18:28.676 App Name[5510:60b] error code.. 1
2015-06-22 11:18:28.679 App Name[5510:60b] updateContact FAILED - failed to execute command insert into url_preference (name) values ( 'http://www.google.lk' )
I've placed the database file in the project folder as shown below;
I can't seem to figure out what I'm doing wrong. Please help.
Is it possible this is a file permissions problem? I would suggest right-clicking the webcontentdb.sqlite file in Finder, select Get Info, and under Sharing & Permissions make all users have Read & Write privileges.
If that doesn't work, I would use an SQLite browser app to verify that the database file can be written to and is not corrupted in any way.

Insert data into sqlite database

I'm insert data into sqlite database and I've seen NSLog(#"DONE") on my console result, but I don't see the data update in my sqlite database file. Pls help me !!!
Here my code to save data:
- (void)saveData:(NSString *)_Id
{
sqlite3_stmt *statement;
NSString *_databasePath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.db"];
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO MyTable (id) VALUES (\"%#\")", _Id];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(db, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DONE");
} else {
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
You are opening the database in your bundle. The bundle is read-only on the device. You must copy the database to your Documents folder (if it doesn't exist there already) and open it from there.
Also be aware that you're dealing with multiple copies of the database (the one in your project, the one in the bundle and now the one in the device/simulator's Documents folder). Make sure you're checking for the inserted record in the correct database (the one in Documents)
As an aside, you should also check to see that sqlite3_prepare_v2 returned SQLITE_OK and if not, log sqlite3_errmsg.
You should also use ? placeholder in your SQL and bind values using sqlite3_bind_text (or, if it's possibly nil, sqlite_bind_null):
- (void)saveData:(NSString *)_Id
{
sqlite3_stmt *statement;
NSString *bundlePath = [[[NSBundle mainBundle] resourcePath ] stringByAppendingPathComponent:#"data.db"];
NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath = [documentsFolder stringByAppendingPathComponent:#"data.db"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:documentsPath isDirectory:NO]) {
NSError *error;
if (![fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error]) {
NSLog(#"database copy failed: %#", error);
}
}
const char *dbpath = [documentsPath UTF8String];
if (sqlite3_open(dbpath, &db) == SQLITE_OK) {
const char *insertSql = "INSERT INTO MyTable (id) VALUES (?)";
if (sqlite3_prepare_v2(db, insertSql, -1, &statement, NULL) != SQLITE_OK) {
NSLog(#"prepare error: %s", sqlite3_errmsg(db));
}
// bind a value to the ? placeholder in the SQL
if (_Id) {
if (sqlite3_bind_text(statement, 1, [_Id UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
NSLog(#"bind text error: %s", sqlite3_errmsg(db));
}
} else {
if (sqlite3_bind_null(statement, 1) != SQLITE_OK) {
NSLog(#"bind null error: %s", sqlite3_errmsg(db));
}
}
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(#"DONE");
} else {
NSLog(#"Failed to add contact: %s", sqlite3_errmsg(db));
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
Most people move that "if database doesn't exist in documents, then copy it from the bundle and open it from there" logic inside a dedicated openDatabase method, but hopefully this illustrates the idea.

Issue in deleting raw from table sqlite

this is what i am doing in header
static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
#implementation SQLAppDelegate
#synthesize window;
#synthesize navigationController;
#synthesize coffeeArray;
this is what i am using for deleting raw
- (void) removeCoffee:(NSNumber *)coffeeObj {
NSLog(#"coffeeObj%#",coffeeObj);
int myInteger = [coffeeObj integerValue];
NSLog(#"myInteger%d",myInteger);
// print this myInteger0
NSLog(#"%#",coffeeArray);
//print object
if (sqlite3_open([self getDBPath], &database) == SQLITE_OK)
{
NSLog(#"myInteger%#",[self getDBPath]);
NSString *sql = [NSString stringWithFormat: #"delete from Coffee where CoffeeID =%d",myInteger];
const char *del_stmt = [sql UTF8String];
NSLog(#"%#",del_stmt); // getting print
// print this delete from Coffee where CoffeeID =0.
sqlite3_prepare_v2(database, del_stmt, -1, & deleteStmt, NULL);
NSLog(#"sqlite3_step(deleteStmt) == SQLITE_DONE%#",sqlite3_step(deleteStmt) == SQLITE_DONE);
// this print null
if (sqlite3_step(deleteStmt) == SQLITE_DONE)
{
//NSLog(#"hi") this is not getting print
} else {
//NSLog(#"hi") this is getting print
}
sqlite3_finalize(deleteStmt);
sqlite3_close(database);
[coffeeArray removeObjectAtIndex:myInteger];
NSLog(#"%#",coffeeArray);
// object is deleted
}
}
my table is like below
table name = Coffee
CoffeeID(INTEGER)=0
CoffeeName(VARCHAR)=Latte
Price(REAL)=2.99
where thing runs perfectly object get deleted from array and thats why its not appearing on table cell. but its not getting deleted from database table thats why it when i launch app again then it shows again please help what i am doing wrong.
Before start deleting the object just conform once the database is opened properly or not. Just try like this.
//Setting path
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"database.db"]];
const char *dbpath=[databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *sql = [NSString stringWithFormat: #"delete from Coffee where CoffeeID =%d",myInteger];
const char *del_stmt = [sql UTF8String];
sqlite3_prepare_v2(database, del_stmt, -1, & deleteStmt, NULL);
if (sqlite3_step(deleteStmt) == SQLITE_DONE)
{
} else {
}
sqlite3_finalize(deleteStmt);
sqlite3_close(database);
[coffeeArray removeObjectAtIndex:myInteger];
NSLog(#"%#",coffeeArray);
// object is deleted
}
if(sqlite3_open([[self filepath] UTF8String], &db) == SQLITE_OK)
{
Deletestatement = nil;
if(Deletestatement == nil)
{
const char *sql = "delete from Sqlitemanager2;";
if(sqlite3_prepare_v2(db, sql, -1, &Deletestatement, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating delete statement. '%s'", sqlite3_errmsg(db));
}
if (SQLITE_DONE != sqlite3_step(Deletestatement)) //prathibha for problem in if
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(db));
sqlite3_finalize(Deletestatement);
}
I hope this will help you.

Cannot insert data into sqlite3 in iOS

I am trying to insert text data into sqlite3 database in iOS.
I wrote following codes to save data into sqlite3 database.
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"MgDB.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"File Not Found");
}
if((!sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK))
{
NSLog(#"Error in MyInfo");
}
const char *sql = "Insert into MyDB (name,address,email) values('%#','%#','%#')";
sqlite3_bind_text(sqlStmt, 0, [Name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(sqlStmt, 1, [Address UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(sqlStmt, 2, [Email UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_prepare(database, sql, -1, &sqlStmt, NULL))
{
NSLog(#"Error in Loading database");
}
if (sqlite3_exec(database, sql, NULL, NULL, NULL) == SQLITE_OK)
{
return sqlite3_last_insert_rowid(database);
}
if(sqlite3_step(sqlStmt) == SQLITE_ROW)
{
NSLog(#"ERROR");
}
}
#catch (NSException *exception)
{
NSLog(#"%#",exception);
}
#finally
{
sqlite3_finalize(sqlStmt);
sqlite3_close(database);
}
according to my above code,I return the last insert ROWID to check that inserted or not.
After saved text data in View,the ROWID have increased.
However when i check my database with FireFox sqlite3 tools, there are no any data that i have inserted.
So i stop running and ReRun my app and add data again.
The last insert ROWID is the same with old count.Not increase even one.
I want to know why it's doesn't save any data into sqlite database.
Is there any problem in my code?
Please help me.
Thanks in advance.
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"MgDB.sqlite"];
You can't write to files included in the application bundle. Create (or copy) the database in the Documents directory instead.
See QA1662.

Resources