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)
Related
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));
}
}
I try to insert only two integer variable to my sqlite database. I created a database which name is ups.sqlite, it has a one table (upssTable) and the table have two column. But when I open /Users/ds/Library/Application Support/iPhone Simulator/5.0/Applications/FCB4B455-4B7F-4C47-81B6-AC4121874596/SqliteDeneme.app/ups.sqlite there is no data in ups.sqlite. My code is here:
- (IBAction)buttonClick:(id)sender {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"ups.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
NSLog(#"database path %#",dbPath);
if(!(sqlite3_open([dbPath UTF8String], &cruddb) == SQLITE_OK))
{
NSLog(#"An error has occured.");
}
if(sqlite3_open([dbPath UTF8String], &cruddb) ==SQLITE_OK){
NSString * str1 =#"1";
NSString * str2 =#"1";
const char *sql = "INSERT INTO upssTable (column1, column2) VALUES (?,?)";
NSInteger result = sqlite3_prepare_v2(cruddb,sql, -1, &stmt, NULL);
NSLog(#"upss %s\n", sqlite3_errmsg(cruddb));
if(result == SQLITE_OK)
{
sqlite3_bind_int(stmt, 1, [str1 integerValue]);
sqlite3_bind_int(stmt, 2, [str2 integerValue]);
}
else
{
NSAssert1(0, #"Error . '%s'", sqlite3_errmsg(cruddb));
}
sqlite3_reset(stmt);
sqlite3_finalize(stmt);
sqlite3_close(cruddb);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"ups.sqlite"];
}
How can I solve this problem? Please help me. Thanks for your reply.
You havent used sqlite3_step() at all. Try this way...
sqlite3 *database;
dbPath=[self.databasePath UTF8String];
if(sqlite3_open(dbPath,&database)==SQLITE_OK)
{
const char *sqlstatement = "INSERT INTO upssTable (column1, column2) VALUES (?,?)";
sqlite3_stmt *compiledstatement;
if(sqlite3_prepare_v2(database,sqlstatement , -1, &compiledstatement, NULL)==SQLITE_OK)
{
NSString * str1 =#"1";
NSString * str2 =#"1";
sqlite3_bind_int(compiledstatement, 1, [str1 integerValue]);
sqlite3_bind_int(compiledstatement, 2, [str2 integerValue]);
if(sqlite3_step(compiledstatement)==SQLITE_DONE)
{
NSLog(#"done");
}
else NSLog(#"ERROR");
sqlite3_reset(compiledstatement);
}
else
{
NSAssert1(0, #"Error . '%s'", sqlite3_errmsg(cruddb));
}
sqlite3_close(database);
}
You are creating your sqlite3 statement, but you aren't actually executing it using sqlite3_step().
Also you appear to be opening the database twice?
I am using below code ..in some statement which works fine with the Simulator but does not work with the device..it gets fails in the IF statement but works fine with the simulator..
what can be the issue .. please help
DB PAth
-(void) openDB {
NSString *databaseFilename = #"A.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseFilename];
NSLog(#"file address %#",databasePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:databasePath error:nil];
//copying
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseFilename];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
if (sqlite3_open([databasePath UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
}
}
and code is
sqlite3_stmt *statement;
NSString *sql;
sql=#"INSERT into db values(?,?)";
if (sqlite3_prepare_v2(db1, [sql UTF8String], -1, &statement, nil) == SQLITE_OK){
sqlite3_bind_text(statement, 1, [A.text UTF8String], -1, NULL);
sqlite3_bind_text(statement, 2, [B_text.text UTF8String], -1, NULL);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
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
I have built an sqlite3 database on the device. When I retrieved it to the pc and tried to open it through Xcode, I got result_code 14, cannot open database.
I need to open this database and read from it while it exist on the mac. I was able to access it and read from it when it was on the device.
Try this code
Create datbase... in Doc Directory..
-(void)createdatabase
{
NSString *databaseName = #"Card.sqlite"; // Name Of DataBase.
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = documentPaths[0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager] ;
success = [fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
Opening database and aceesss it's content..
- (void)getData
{
sqlite3 *database;
NSString *databasePath;
NSString *databaseName;
NSString *documentsDir;
NSArray *documentPaths;
databaseName = #"Card.sqlite";
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = documentPaths[0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement = "SELECT * FROM Master";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
[ID removeAllObjects];
[Name removeAllObjects];
[Image removeAllObjects];
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[ID addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
[Name addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 1)]];
[Image addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 2)]];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
[tblView reloadData];
}
You can use SQLite Manager Firefox Plugin to read database, or use SQLiteManager
You can find your .sqlite file at : ~/Library/Application\ Support/iPhone\ Simulator/User/Applications/ ...