SQLite error "no such table" - ios

I'm getting this error:
2015-06-11 12:06:42.103 actividadFinaliOS1[25425:1798557] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while inserting data. 'no such table: recordatorios''
and I'm pretty sure the table is created. Check my code:
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: #"recordatorios.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
if (!_todoItems) {
_todoItems = [NSMutableArray new];
}
_databasePath = [[NSBundle mainBundle] pathForResource:#"recordatorios" ofType:#"sqlite"];
if (sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK)
{
_consulta = [NSString stringWithFormat: #"SELECT * FROM recordatorios"];
const char *query = [_consulta UTF8String];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, query, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW) {
char *item = (char *) sqlite3_column_text(statement, 0);
NSString* string = [NSString stringWithFormat:#"%s" , item];
[_todoItems addObject:string];
}
sqlite3_finalize(statement);
}else
{
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(_database));
}
sqlite3_close(_database);
}else
{
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(_database));
}
}

Related

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;
}

ios- sqLite not deleting rows

I am trying to delete all the rows in database for that I wrote following codes ..
- (id)init {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"dataBase.sqlite3"];
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];
if (!databaseAlreadyExists){
NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:#"dataBase" ofType:#"sqlite3"];
[[NSFileManager defaultManager] copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
if (sqlite3_open([databasePath UTF8String], &_database) == SQLITE_OK){
}
return self;
}
-(void)deleteAll{
NSString *query = #"DELETE FROM user_info";
sqlite3_stmt *statement = nil;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
NSLog(#"Should delete..");
}
sqlite3_finalize(statement);
sqlite3_close(_database);
}
But when I rebuild the app data data appears. Whats wrong I am doing?
You never call sqlite3_step to actually execute the query.
Also, you close the database in the wrong place. Your close should be done opposite of the open.
First of all, get the database path after that open database
NSString *dbPath1=[SqliteManager getDataBasePath];
if (sqlite3_open([dbPath1 UTF8String], &database) == SQLITE_OK)
{
NSLog(#"opened the data base");
const char *sql = "delete from travels";
if(sqlite3_prepare_v2(database, sql, -1, &deletestmt, NULL) == SQLITE_OK)
if(SQLITE_DONE != sqlite3_step(deletestmt))
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(database));
else
isdeleted=YES;
}
sqlite3_reset(deletestmt);
sqlite3_close(database);
write in ur method inside.....
Getting Database Path....
+(NSString *)getDataBasePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSLog(#"file Path is %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"Give ur Sqlite Filename"];
}
Try a conditional if:
if(sqlite3_prepare_v2(database, sql, -1, &deletestmt, NULL) != SQLITE_OK)

Always fail if (sqlite3_step(statement) == SQLITE_DONE)

This is the code that I have used in Appdelegate.m to copy the database
- (void) copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"LocalSongs.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
And this is used to get the DBPath
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"LocalSongs.sqlite"];
}
This is my playlist Insert method
-(NSString *)InsertPlaylist :(NSString *)PlaylistName
{
NSLog(#"passed");
NSString *status;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath=[[NSString alloc]initWithString:[documentsDir stringByAppendingPathComponent:#"LocalSongs.sqlite"]];
NSLog(#"Database Path %#",dbPath);
sqlite3_stmt *statement;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSLog(#"open");
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO LOCALPLAYLIST (PLAYLISTNAME,getdate()) VALUES (\"%#\")",PlaylistName];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status=#"Playlist Created";
}
else
{
status=#"Error occured";
}
return status;
}
}
The problem I have is this prepare_v2 is always become notdone. It always execute the else part.
if (sqlite3_step(statement) == SQLITE_DONE)
What is the problem with this? Please help me
I think you have an error with your query: you are supposed to put a column name in the place you put getdate(), i.e. instead of
INSERT INTO LOCALPLAYLIST (PLAYLISTNAME,getdate()) VALUES (\"%#\")
you should use something like
INSERT INTO LOCALPLAYLIST (PLAYLISTNAME,MYDATECOLUMN) VALUES (\"%#\",getdate())
After sqlite3_prepare_v2 the statement pointer is NULL?
Compare the return values of sqlite3_prepare_v2 and sqlite3_step with the ones in http://www.sqlite.org/c3ref/c_abort.html to get a better insight on what's going wrong

Resources